Reputation: 3
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?
Upvotes: 0
Views: 38
Reputation: 46
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.
Upvotes: 3