DEV Community

khoinguyenkc
khoinguyenkc

Posted on

How to: implement selected/highlighted buttons/boxes

This is one of those features that seems simple in hindsight but it's actually not easy to come up with a clean solution. Here's a clean solution.

Define the problem:
Basically you have a bunch of elements, only one of them can be selected/highlighted at any given time.

The key insights are

  1. You must have a state OUTSIDE of all of these elements
  2. And all these elements have READ access to that state
  3. All elements have WRITE access to that state

This example uses functional component.

We initialize a state like this:
const [ clickedBox, setClickBox ] = "";

Then we assign each component 2 things:

<
Box
active={clickedBox == "box1"}
onClick={ (event) => setClickBox("box1")
}
/>

<
Box
active={clickedBox == "box2"}
onClick={ (event) => setClickBox("box2")}
/>

<
Box
active={clickedBox == "box3"}
onClick={ (event) => setClickBox("box3")
}
/>

We give each component an attribute named "active", its value will be true or false.
We also give each component a callback function that gets called if the box is clicked.

Inside the Box component, you can use the active attribute's true/false status to conditionally display each box as selected/highlighted.

Top comments (0)