Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!