The HTML is rerendered after click and displays the chosen content.
We use a stateful variable.
The stateful variable (here, a boolean) is called ‚condition‘ 😉 :
const [condition, setCondition] = useState(false);
The #useEffect method to react on variable state change:
useEffect(() => {
...
},[condition]);
The methods for the buttons:
const handleClickSomething01 = () => setCondition(true);
const handleClickSomething02 = () => setCondition(false);
The returned HTML:
if (condition === true) {
return (
<div>
<Button variant="contained"
color="primary"
onClick={handleClickSomething02}>
Primary
</Button>
<Button variant="contained"
color="secondary"
onClick={handleClickSomething01}>
Secondary
</Button>CONDITION fullfilled
</div>
);
} else {
return (
<div>
<Button variant="contained"
color="primary"
onClick={handleClickSomething02}>
Primary
</Button>
<Button variant="contained"
color="secondary"
onClick={handleClickSomething01}>
Secondary
</Button>CONDITION not fulfilled
</div>
);
}
You will notice that this example uses duplicated code (sort of, a few details differ).
Why did I do this?
I have debugged so many unmaintainable Frontends during the last two decades and nearly always the obstacles where too many detailed conditions in the HTML.
Instead, by using IF/ELSE and clearly depict the HTML without conditional renderings within, the Code will be easier to maintain in the long run.
Of course, this is my personal experience and also a matter of Clean Code paradigms.
In some cases, am using inline conditions, inside the HTML lines, too. But as we Architects like to say: IT DEPENDS 😉