I have a layout with two buttons. I want to be able to click on each button to display its content. Also each button should be a toggle to either display the contents or not.
function Update() {
const [showFirst, setShowFirst] = useState(false);
const [showSecond, setShowSecond] = useState(false);
return (
<Wrapper>
<main
<h3>CHANGE FACILITY</h3>
<div style={{ display: "flex", justifyContent: "space-between"}}>
<Link
onClick={() => setShowFirst(!showFirst)}
>
First content
</Link>
<Button
onClick={() => setShowSecond(!showSecond)}
>
Second content
</Button>
</div>
</div>
<main>
<div style={showSecond? {display:"none"} : {display:"block"}}>
{showFirst && (<h3>Ist facility</h3>)}
</div>
<div style={showFirst? {display:"none"} : {display:"block"}}>
{showSecond && (<h3>2nd facility</h3>)}
</div>
</Wrapper>
);
}
When I click on the ShowFirst button it renders both content and the ShowSecond button does not toggle. Please I need a guide to make each button display its content when its button is clicked and also toggle action on each button click.
CodePudding user response:
You seem to trying the following.
function Update() {
const [showFirst, setShowFirst] = useState(false);
const [showSecond, setShowSecond] = useState(false);
return (
<Wrapper>
<main>
<h3>CHANGE FACILITY</h3>
<div style={{ display: "flex", justifyContent: "space-between"}}>
<button onClick={() => {
setShowFirst(!showFirst);
setShowSecond(false);
}}>
First content
</button>
<button onClick={() => {
setShowSecond(!showSecond);
setShowFirst(false);
}}>
Second content
</button>
</div>
</main>
{
showFirst && (
<div>
<h3>Ist facility</h3>
</div>
)
}
{
showSecond && (
<div>
<h3>2nd facility</h3>
</div>
)
}
</Wrapper>
);
}
CodePudding user response:
Try the following code. You are already pretty close.
function Update() {
// Set tabIndex to 1 by default to show the first tab on load
const [tabIndex, setTabIndex] = useState(1);
return (
<Wrapper>
<main>
<h3>CHANGE FACILITY</h3>
<div style={{ display: "flex", justifyContent: "space-between"}}>
<button onClick={() => setTabIndex(1)}>
First content
</button>
<button onClick={() => setTabIndex(2)}>
Second content
</button>
</div>
</main>
{
tabIndex === 1 && (
<div>
<h3>Ist facility</h3>
</div>
)
}
{
tabIndex === 2 && (
<div>
<h3>2nd facility</h3>
</div>
)
}
</Wrapper>
);
}