user15603995
user15603995

Reputation:

How to switch between useStates instead of adding new

I need to switch between 3 of mine different components:

const [showOne, setShowOne] = useState(false);
const [showTwo, setShowTwo] = useState(false);
const [showThree, setShowThree] = useState(false);

So when showOne is clicked, the One component will show up, but when showTwo/showThree gets clicked, showOne will hide and component Two/Three will show up instead.

Current solution:

<div className="box" onClick={() => setShowOne(!showOne)}></div>
<div className="box" onClick={() => setShowTwo(!showTwo)}></div>
<div className="box" onClick={() => setShowThree(!showThree)}></div>

{showOne && (
             <One />
            )}
{showTwo && (
             <Two />
            )}
{showThree && (
             <Three />
            )}

Current behaviour:

When clicked showOne -> component One shows up, when after showTwo is clicked, component Two will be added under component One. (the same for showThree - Three)

Expected Behaviour:

Click showOne - shows One, click showTwo - One disappear and Two will shows up ( the same showThree - Three)

Upvotes: 0

Views: 18

Answers (1)

Ravi Lamichhane
Ravi Lamichhane

Reputation: 11

Create a to show state.

const [toShow, setToShow] = useState(0);

You can set the initial state to 1 ,2 or 3 if you like.

and render the boxes as follows

{toShow ===1 && <One />}
{toShow ===2&& <Two />}
{toShow ===3&& <Three />}

Upvotes: 1

Related Questions