Home > Software design >  Can multiple elements that share a state have an update only propagate to a single element
Can multiple elements that share a state have an update only propagate to a single element

Time:12-07

Say I have a state:

const [isLess, setIsLess] = useState(true);

And two elements sharing this state:

// some content
<span onPointerDown{changeStateToSeeLess}>
    See All <ExpandIcon/>
</span>

// some content
<span onPointerDown{changeStateToSeeLess}>
    See All <ExpandIcon/>
</span>

Can I update the state of only one span when it is clicked?If not how can I update only one span to "See Less" on a click(pointerdown)?

CodePudding user response:

What you have is a boolean. What you want is an array. (Or object, any structure which can hold multiple values.)

For example, consider this state:

const [isLess, setIsLess] = useState([true, true]);

Now isLess contains two values (identified only by their position in the array, for demo purposes). Those two values can then be used independently. For example:

<span onPointerDown={() => changeStateToSeeLess(0)}>
  See All <ExpandIcon/>
</span>

<span onPointerDown={() => changeStateToSeeLess(1)}>
  See All <ExpandIcon/>
</span>

Here you see that each event handler is providing some identifying value to the change handler. The handler can then use that identifier to know which array value to update:

const changeStateToSeeLess = (id) => {
  setIsLess(isLess.map(x, i) => i == id ? false : x);
};

In this case the callback to map() is checking if the provided id matches the position/index in the array and, if so, sets that value to false. Otherwise it doesn't change the value.

You can expand this in a variety of ways. For example, instead of relying on the array position to identify the element, you can have an explicit identifier. And instead of an array of boolean values, you can have an array of objects which contain identifiers and boolean state values.

  • Related