Home > database >  React. How to change state only to current element after .map method?
React. How to change state only to current element after .map method?

Time:10-30

When all list items are rendered I want that after click only clicked list item has been changed its style.

const [currentStyle, setCurrentStyle] = useState();

array.map(val => (<li style={currentStyle}>{val.name}</li>)

CodePudding user response:

I advise you to make another component for you items, that way it will be easier to manage state for each item

for instance :

function YourComponent() {    
...
const [currentStyle, setCurrentStyle] = useState();
    ...
    array.map(val => (<ItemComponent style={currentStyle}>{val.name}</ItemComponent>)
...
}

function ItemComponent({style, children}) {
   const [changeStyle, setChangeStyle] = useState(false)
   return (
       <li onClick={() => {setChangeStyle(true)}} style={changeStyle ? style : null}>{children}</li>
    )
}

CodePudding user response:

The better way to do that has already been shared by Jimmy. but if you are lazy you can do something like.

Note: Both approaches are different. If you manage that via subcomponents you will have to add extra logic to keep track of clicked items in the parent. (Still recommended)

But if you use this one you can have the clicked Items track in the component itself (clickedItems)

const [currentStyle, setCurrentStyle] = useState();
const [clickedItems, setClickedItems] = useState([]);

array.map((val, index) => (<li onClick={() => 
    setClickedItems(clickedItems.find(i => i===index) ? clickedItems : [...clickedItems, index])}
    style={clickedItems.find(i => i===index) ? currentStyle : null}>{val.name}
</li>)
  • Related