Search code examples
javascriptreactjscomponentsweb-deploymentreact-component

How can I toggle between 3 components in ReactJS


I am having a hard time rendering components conditionally in React. I have successfully rendered 2 components (A and B) conditionally but couldn't find any successful way to add a third component (C) in our case

this is the code for 2 componnets:

function App() {
  const [click, setClick] = useState(true);

  const ShowA = () => setClick(true);
  const ShowB = () => setClick(false);

  return (
    <>
      <br />

      <button onClick={ShowA}>A </button>

      <button onClick={ShowB}>B </button>

      <div className="App">
        {click && <div> A </div>}

        {!click && <div>B</div>}
      </div>
    </>
  );
}

Is there any possible way I can add a third C component so I can toggle between them? I have been trying for 2 days but no success.

This is the link of Codesandbox if anyone's interested

https://codesandbox.io/s/musing-tesla-9gkpw?file=/src/index.js:100-481


Solution

  • You can put as many states as you want:

      function App() {
        const [displayA, setDisplayA] = useState(true);
        const [displayB, setDisplayB] = useState(true);
        const [displayC, setDisplayC] = useState(true);
    
        const showA = () => {
          setDisplayA(true);
          setDisplayB(false);
          setDisplayC(false);
        }
        const showB = () => {
          setDisplayA(false);
          setDisplayB(true);
          setDisplayC(false);
        };
        const showC = () => {
          setDisplayA(false);
          setDisplayB(false);
          setDisplayC(true);
        };
    
        return (
          <>
            <br />
      
            <button onClick={showA}>A</button>
            <button onClick={showB}>B</button>
            <button onClick={showC}>C</button>
      
            <div className="App">
              {displayA && <div>A</div>}
              {displayB && <div>B</div>}
              {displayC && <div>C</div>}
            </div>
          </>
        );
      }
    

    And you can even put other things in your state, like JSX elements:

      function App() {
        const [elementToDisplay, setElementToDisplay] = useState("");
    
        const showA = () => {
          setElementToDisplay(<div>A</div>)
        }
        const showB = () => {
          setElementToDisplay(<div>B</div>)
        }
        const showC = () => {
          setElementToDisplay(<div>C</div>)
        }
    
        return (
          <>
            <br />
      
            <button onClick={showA}>A</button>
            <button onClick={showB}>B</button>
            <button onClick={showC}>C</button>
      
            <div className="App">
              {elementToDisplay}
            </div>
          </>
        );
      }