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

140
Visualizações
Conditional rendering inputs overlap text

I've been trying to make a form where, depending on a switch button, renders one or two different inputs. My code looks like this:

const Test = () => {

const [switchButton, setSwitch] = React.useState(true)

const handleSwitch = () => {setstate(!switchButton)}

return <>
  <Switch checked={switchButton} onClick={() => handleSwitch} />
  {!switchButton ? 
    <>
       <label htmlFor="input_1">Input 1</label>
       <input id="input_1"/>
    </>
     :
    <>
       <label htmlFor="input_2">Input 2</label>
       <input id="input_2" />
       <label htmlFor="input_3">Input 3</label>
       <input id="input_3" />
    </>
  }
</>
}

export default Test;

My issue happens when I enter characters into one input and then switch them: The same characters are shown on my new rendered input. Example here.

Why does this happen? I'm really lost

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

use keys for the elements, so it will not be recognized as the same element as react tries to map elements on each rerender if they were already rendered before. so react sees: 1 input and than 2 inputs and thinks the first input is the same as before.

const Test = () => {
  const [switchButton, setSwitch] = React.useState(true)
  const handleSwitch = () => setSwitch((switch) => !switch)

  return (
    <>
      <Switch checked={switch} onClick={handleSwitch} />
      {!switchButton ? (
        <React.Fragment key="key1">
          <label htmlFor="input_1">Input 1</label>
          <input id="input_1"/>
        </>
      ) : (
        <React.Fragment key="key2">
          <label htmlFor="input_2">Input 2</label>
          <input id="input_2" />
          <label htmlFor="input_3">Input 3</label>
          <input id="input_3" />
        </>
      )}
   </>
)}

export default Test;

but anyway it would be better to use a controlled input. something like this:

const [value, setValue] = React.useState(true)

<input value={value} onChange={(e) => setValue(e.target.value)}/>
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