Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rendering using the select tag on React js error

I’ve built 2 functions that return JSX content and then i made some logic to return each function once based on the user choice:

const Register = () =>{

const [value, setMyValue] = useState()




function Zeff(){
return(
  <div>
    <h1>Hello Zeff!</h1>
 </div>   
)
}

function Jerry(){
  return (
  <div>
    <h1>Hello Jerry!</h1>
</div>
  
)
}


const Choice = () =>{

if (value){
return <Zeff />
}else{
return <Jerry />
}
}



return(
    <div>
      <Navbar />
  <select onChange={(e)=>{setMyValue(e.target.value)}} class="form-select" aria- 
  label="Default select example">

  <option value="false">Jerry</option>
  <option value="true">Zeff</option>
  </select>

  <Choice />
  </div>
  </div>    
  )
  }
  export default Register

My problem is when i load the page it shows up the "Hello Jerry!" and when i choose Zeff in the select tag it also changes correctly to "Hello Zeff!" but once i go back again to Jerry it remains "Hello Zeff!"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your problem is value is a string, so if(value) always returns true which is Zeff.

For the fix, you should have to check string matches like if(value === "true") instead.

Side note that I’ve also moved Zeff, Jerry, and Choice out of Register for avoiding re-renderings.

function Zeff() {
  return (
    <div>
      <h1>Hello Zeff!</h1>
    </div>
  );
}

function Jerry() {
  return (
    <div>
      <h1>Hello Jerry!</h1>
    </div>
  );
}

const Choice = ({ value }) => {
  if (value === "true") {
    return <Zeff />;
  } else {
    return <Jerry />;
  }
};

const Register = () => {
  const [value, setMyValue] = useState();

  return (
    <div>
      <Navbar />
      <select
        onChange={(e) => {
          setMyValue(e.target.value);
        }}
        class="form-select"
        aria-label="Default select example"
      >
        <option value="false">Jerry</option>
        <option value="true">Zeff</option>
      </select>

      <Choice value={value} />
    </div>
  );
};
export default Register;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading