Search code examples
javascriptreactjsweb-frontend

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>

  );
};

Solution

  • 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(null); //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.