'How to render conditionally depending on which button is clicked?
I'm new to ReactJS and I want to have a conditional rendering like the code below
I read the doc but I was a bit confused.
Do I have to handle true/false for each buttons similar to the doc?
render() {
return (
<div>
<h1>Render "ABC"/"DEF"/"XYZ" depends on which button is clicked</h1>
<Button>ABC</Button>
<Button>DEF</Button>
<Button>XYZ</Button>
</div>
)
}
Solution 1:[1]
You can use a map (an object in JS) with key-boolean pair if you want to control multiple button states. Like
const [buttonStates, setButtonStates] = useState({
"ABC": false,
"DEF": true,
"XYZ": true,
});
Then
{buttonStates["ABC"] && <>"ABC"</>}
{buttonStates["DEF"] && <>"DEF"</>}
{buttonStates["XYZ"] && <>"XYZ"</>}
Solution 2:[2]
You can control this situation with simply one state. For Example :
const [whicheBtn, setWicheBtn] = useState("btnA")
and in your component, you should check for the value of the whicheBtn
state.
render() {
return (
<div>
<h1>Render "ABC"/"DEF"/"XYZ" depends on which button is clicked</h1>
{whicheBtn == "ABC" && <Button>ABC</Button> }
{whicheBtn == "DEF" && <Button>DEF</Button>}
{whicheBtn == "XYZ" && <Button>XYZ</Button> }
</div>
)
}
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 | Han Moe Htet |
Solution 2 | Masroor Hosseini |