Home > database >  Select one item at a time without DOM manipulation in React.js
Select one item at a time without DOM manipulation in React.js

Time:10-18

I am trying to create something like custom select. Only one item should be selected at a time. Clicked element becomes highlighted by adding corresponding css class "active". The problem is that the only way I know to remove the class from other, already selected elements is through 'querySelector' - select all items with same class and remove 'active' class from them all. And this would be a DOM manipulation, which is not a proper way to work in ReactJS, right?

What would be a right way to work around this problem?

My code so far:


const size = ['s', 'm', 'l']

const handleSelectSize = (value) => {
  setChosenSize(value);
}

<div className='size-variants'>{size.map(value => {
   return (
      <div className='size-item' onClick={() => handleSelectSize(value)} value={value} key={value}>{value.toUpperCase()}</div>
     )
   })}
</div>```

CodePudding user response:

I understood from your code that you have a state of chosenSize that houses the last selected size, so simply check each render if any value matches the last selected value and add the active class to it

const size = {'s', 'm', 'l'}

const handleSelectSize = (value) => {
  setChosenSize(value);
}

<div className='size-variants'>{size.map(value => {
   return (
      <div className=`size-item ${chosenSize == value && 'active'}` onClick={() => handleSelectSize(value)} value={value} key={value}>{value.toUpperCase()}</div>
     )
   })}
</div>

  • Related