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!"

>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;

Leave a Reply