简体   繁体   中英

Conditional render 1 of 3 components on button click (react)

I'm new to react and been struggling to figure out how to render the components inside the container depending on which button has been clicked.

I've set the state to false, then on the button click set it to true then used a ternary operator to show or set the component to null but won't work when the next button is clicked because the state is already set to true.

any help in the right direction would be appreciated:)

const AboutUs = () => {

  const [VisDetails, setVisDetails] = useState(false);

  return (

<Button>Personal Details</Button>
<Button>Bio</Button>
<Button>Qualifications</Button>

Container className={classes.container}>

<PersonalDetails />
<ProfileBio />
<ProfileQualifications />

</Container>

  );
};

Based on the button click selected state receive the value which will be used in showSelectedOption() to return the right component.

const AboutUs = () => {
  const [selected, setSelected] = useState('');

const showSelectedOption = () => {
  switch(selected) {
    case 'details':
      return  <PersonalDetails />;
    case 'bio':
      return  <ProfileBio />;
    case 'qualif':
      return  <ProfileQualifications />;
    default:
      return '';

  }
}

return (
   <Button onClick={() => setSelected('details')}>Personal Details</Button>
   <Button onClick={() => setSelected('bio')}>Bio</Button>
   <Button onClick={() => setSelected('qualif')}>Qualifications</Button>

   Container className={classes.container}>
      {showSelectedOption()} 
   </Container>
  );
};

I think the best thing to do in this case is save the state depending on what content should be showing and then update that state on button click.

Something like this

const AboutUs = () => {

  const [selected, setSelected] = useState(//Here goes the default value you 
                                           //want to show, or null if you want no render);

  return (
    <Button onClick={() => { setSelected('personaldetails') }}>Personal Details</Button>
    <Button onClick={() => { setSelected('bio') }}>Bio</Button>
    <Button onClick={() => { setSelected('qualif') }}>Qualifications</Button>

    Container className={classes.container}>

    {
      (selected == 'personaldetails') ? <PersonalDetails /> : null
    }
    {
      (selected == 'bio') ? <ProfileBio /> : null
    }
    {
      (selected == 'qualif') ? <ProfileQualifications /> : null
    }

    </Container>
  );
};

You could use a switch() but I like the inline if statement, easier to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM