Home > OS >  Toggle different components from multiple buttons (nextjs)
Toggle different components from multiple buttons (nextjs)

Time:12-28

I'm trying to build an component that render different components based on which button the user clicks.

this is what the "pages" are:

`

    const navigation = [
      { name: "EOQ", return: "<EOQgraph />" },
      { name: "ROP", href: "<ROPgraph />" },
      { name: "Table", href: "<Table />" },
      { name: "ROC SS", href: "<ROCSSgraph />" },
      { name: "Table SS", href: "<TableSS />" },
    ]

`

This is the function and the UseState that needs to receive the key (Not all of the components are in yet):

`

  const [toggle, setToggle] = useState('')

const wantedGraph = (value) => {

    switch (value){
      case  "EOQ":
        return setToggle(<EOQgraph />);
      case  "ROP":
        return setToggle(<ROPgraph />);

`

And the return that uses a .map to display all the buttons: `

        return(
            <div>
                {navigation.map((item) => (
           <button type="submit" 
                   className={'btn btn-outline-dark btn-md'} 
                   key={item.name}
                   onClick = {() => setToggle(wantedGraph(item.name))}
                   >
               {item.name}
           </button>
            ))}
                <div>
                  { toggle }
                </div>
            </div>
        )

`

Currently nothing is showing inside of the component.

The page works perfectly and the buttons are there. UseState is also working, but as soon as you press on a button, the component doesn't render.

I should add that I'm also using Graph.js and each component is in a different page and i'm importing all of them.

CodePudding user response:

This is happening because you are setting toggle's value to undefined in your button's onClick handler. It is getting set to undefined because wantedGraph returns the value gotten from calling setToggle, which does not return anything, i.e. undefined.

You should either change wantedGraph to return the component you want, e.g.:

const wantedGraph = (value) => {
    switch (value) {
      case "EOQ":
        return <EOQgraph />
      case "ROP":
        return <ROPgraph />
    }
  }

Or change the onClick handler to not call setToggle:

return (
    <div>
      {navigation.map((item) => (
        <button type="submit"
          className={'btn btn-outline-dark btn-md'}
          key={item.name}
          onClick={() => wantedGraph(item.name)}
        >
          {item.name}
        </button>
      ))}
      <div style={{ color: 'white' }}>
        {toggle}
      </div>
    </div>
  )
  • Related