Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
How to optimally render Radios and bind changing values with React and JSX?

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?
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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> ...
      </>
    )
  }
);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda