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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.