'Conditionally render components in React

I'm new to React and still learning my way around. I have a react page that renders a component that has 5 buttons. I'm trying to render another component based on which button is clicked. How can I achieve this?



Solution 1:[1]

You can achieve this by state usage. Useful for this goal being useState hook and conditional rendering in React. More info about it: https://reactjs.org/docs/hooks-state.html

Example for your question:

function MyComponent() {
  const [isTextVisible, setIsTextVisible] = useState(false);
  
  return (
     <>
       <button onClick={() => { setIsTextVisible(true) }}>Click on Me!</button>
       { isTextVisible && <p>I am visible only after button click!</p> }
     <>
  )
}

In this example, when the button is clicked, the isTextVisible state will be filled with the true value. When isTextVisible will be equal true - text in condition will be visible. Text easily can be replaced by another your component.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gl-pv