I’ve a state like this
const [inputMode, setInputMode] = useState(1);
This is what I’m doing to render and bind value to the state.
const renderRadios = () => { if (inputMode == 1) { return ( <> <input defaultChecked type="radio" value="1" onClick={e => setInputMode(parseInt(e.target.value))} /> <input type="radio" value="2" onClick={e => setInputMode(parseInt(e.target.value))} /> </> ); } else if (inputMode == 2) { return ( <> <input type="radio" value="1" onClick={e => setInputMode(parseInt(e.target.value))} /> <input defaultChecked type="radio" value="2" onClick={e => setInputMode(parseInt(e.target.value))} /> </> ); } } return( <h1>Result</h2> {renderRadios()} );
Is there any alternate much simpler approach? I prefer
- Inline rendering within return statement, rather than using a separate arrow function to render radios *using multiple if-else ladders (Any way to inline it?)
- Is onClick binding correct to set value to the state? I tried onChange but it’s not working somehow
- This works fine for me but I’m searching for a performant optimized version of the code.
- Here, I’m setting defaultChecked based on if-else cases, What is the best way to inline this and shrink code?
Advertisement
Answer
It looks like all you really need to do is make the value of the defaultChecked
prop truthy or falsey, depending on the state.
onChange
works just fine, and since you already know the value of the inputs will be 1 or 2, you can use those directly instead of going through parseInt(event.target.value)
.
function App() { return ( <> <h1>Result</h1> <input defaultChecked={inputMode === 1} className="form-check-input" type="radio" name="inputMode" value="1" id="tapanddone" onChange={e => setInputMode(1)} /> <input defaultChecked={inputMode === 2} className="form-check-input" type="radio" name="inputMode" value="2" id="logvalue" onChange={e => setInputMode(2)} /> </> ); }
Live demo:
function App() { const [inputMode, setInputMode] = React.useState(1); console.log('inputMode', inputMode); return ( <React.Fragment> <h1>Result</h1> <input defaultChecked={inputMode === 1} className="form-check-input" type="radio" name="inputMode" value="1" id="tapanddone" onChange={e => setInputMode(Number(e.target.value))} /> <input defaultChecked={inputMode === 2} className="form-check-input" type="radio" name="inputMode" value="2" id="logvalue" onChange={e => setInputMode(Number(e.target.value))} /> </React.Fragment> ); } ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>
(Any way to inline it?)
If you couldn’t use the above approach, yes, eg:
return ( <h1>Result</h2> { inputMode === 1 ? ( <> <input> ... </> ) : ( <> <input> ... </> ) } );