Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rerender every child components after parent state changes React

Hello i am currently facing this situation.
here is the simplified version of the code.

const Parent = ({prop}) => {
 const [listOfBool, setListOfBool] = useState([true, false])
 const handleCallback = (e, ev) => {
    var cloneListOfBool = [...listOfBool]
    cloneListOfBool[e] = ev
    setListOfBool(cloneListOfBool)
 }
 return (
    <div>
        <p>{prop}</p>
        <div>{listOfBool.map((bool, idx) => <Child key={idx} prop1={idx} active={bool} parentCallback={handleCallback} />)}</div>
    </div>
 )
}

this is the child component

const Child = ({prop1, active, parentCallback}) => {
const [active, setActive] = useState(active)
const setThis = (e) => {
    if (active === true){
        parentCallback(e, false)
        setActive(false)
    } else {
        parentCallback(e, true)
        setActive(true)
    }
}

return (
    <>
        <p className={`${active === true ? 'selected' : ''}`} onClick={() => setThis(prop1)}>{prop1}</p>
    </>
)

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

prop1 is a number, i use that number to acces the array and change its value.

in the parent i set the list of boolean values, i map through them and i create the childrens. Now when the props of the parent changes, i would like to re render every child . Everything works as i want except for this part. Later on i will need to make a request to get the list of bools. Can you tell me waht is wrong, i have tried a couple of different solutions with no succes. Thank You

>Solution :

You can use key to force a react component to rerender.

So in this case if prop is the parent prop that you want to listen to, you can do something similar to:

  <div>
   {listOfBool.map((bool, idx) => (
      <Child
        key={`idx_${prop}`}
        prop1={idx}
        active={bool}
        parentCallback={handleCallback}
      />
    ))}
  </div>

May I ask why you want the component to rerender on a prop it does not use? As much as possible, you should just pass that property to the child, as a setup like this implies some sort of side effect that might be hard to spot.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading