Home > Blockchain >  React find all unselected elements of the array
React find all unselected elements of the array

Time:04-04

So basically I have an array of objects that contains name, id and a isSelected value which is false at first. when I map this array on my component and display them I can detect the index of the element which was selected with a SelectHandler function that I call inside the onClick={}.

What I want to do is make the isSelected true for the element which is selected and false for all the rest. because only one element of the array can me selected at a time. And then after the selected element style will change.

I was wondering how can I achieve this and also if I'm supposed to use the onClick method or if I should use another method?

enter image description here

enter image description here

CodePudding user response:

You could use a single state variable tracking which element is currently selected, e.g.

const [selectedId, setSelectedId] = useState();

Then, in onClick

onClick={() => setSelectedId(id)}

And in the styling for the element, apply styling depending on if selectedId is equal to the element's own id

CodePudding user response:

Looking at your code, and also agreeing that you could make use of a single state variable to set an active id, I would say you could avoid using this isSelected boolean object property all together for this particular instance, like so:

const UserProfileCard = (): JSX.Element => {
  const [selectedId, setSelectedId] = useState<number | undefined>();

  const MockSearchOptions = [
    { id: 1, option: 'Room Name' },
    { id: 2, option: 'Org Name' },
    { id: 3, option: 'Etc.....' },
  ];

  return (
    <div className="user-profile-card__search_options">
      {MockSearchOptions.map((item, index) => {
        const activeClassTag = selectedId === item.id ? '-selected' : '';
        const { id, option } = item;

        return (
          <div
            key={`${id}-${index}`}
            onClick={() => setSelectedId(id)}
            className={`user-profile-card__search-option${activeClassTag}`}
          >
            <p>{option}</p>
          </div>
        );
      })}
    </div>
  );
};

CodePudding user response:

first of all dont send the index of the object, index can change if you sort or change your array. Just send the id of clicked object.

onClick={() => selectHandler(item.id)}

const selectHandler = (id) => {
    const tempArr = [...searchOptions]
    tempArr.forEach(item => {
         if(item.id === id) {
               item.isSelected = !item.isSelected;
         } else {
               item.isSelected = false;
         }
    })
    //if you use useState:
    setSearchOptions([...tempArr])
}
  • Related