Search code examples
reactjscomponents

Prevent update of all components on button click


I have an array of objects and displayed them using map. A '+' button associated with each component. I want to update the count of a specific component on button click. I tried with the following code. However, it is updating the count of all the other components also. What can I do to fix this?

import { useState } from 'react';
import { people } from './Data.js';

function App() {
  const[count,setCount]=useState(0)
  const updateCount=()=>{
    setCount(count+1)
  }
  return (
  <div>
    <h4>List of Items</h4>
    {
      people.map((item)=>{

        return (
        <div key={item.id}>count:{count}
        <button onClick={()=>updateCount}>+</button>
        </div>
        )
        })
    }
    </div>
  );
}

export default App; 

Solution

  • You need to manage the state individually. Here's a possible alternative, hope it helps.

    import React,{ useState } from 'react';
    import { people } from './Data.js';
    
    function PeopleItem(props) {
    const[count,setCount]=useState(0)
    const updateCount=()=>setCount(count+1)
    const {item} = props
    return <div>count:{count}
          <button onClick={updateCount}>+</button>
      </div>
    }
    
    
    export function App() {
    return (
    <div>
      <h4>List of Items</h4>
      {
        people.map((item)=> <PeopleItem key={item.id} item={item}/>)
      }
      </div>
    );
    }