Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
React. How to change state only to current element after .map method?

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>)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>
    )
}
about 4 years ago · Juan Pablo Isaza Report

0

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>)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!