0

I'm trying to create a new dynamic component that receives a value from its parent and is added to an array. However, that component prop must update itself and change in all the components inside the array when the original value change, but use useState don“t change the value in the inside the component and only use the value that was added when was added to the array.

I need to know how to send the value to the child components that are constantly updated in all of them.

Here is my code:

parent:

import React, {useState} from 'react';

import Child from './TestComponentChild';
export default function Parent(){
    
    const [var1, setVar1] = useState(0);
    const [array, setArray] = useState([]);
    
    return(
        <div>
            {array}
            <button onClick={() => { setArray([...array , <Child var2={var1}/> ]) }}>TestButton1</button>
            <button onClick={() => { setVar1(var1 + 1)}}>TestButton2</button>
        </div>
    )
}

Child

export default function Child(props){
    
    return(
        <div>
            {props.var2}
        </div>
    )
}

1 Answers1

0

Instead of storing the components themselves in the array, just store the number of components that you need to render and dynamically render them in-place. For example:

const [var1, setVar1] = useState(0);
const [components, setComponents] = useState(0);

return(
    <div>
        {(new Array(components)).fill(<Child var2={var1}/>)}
        <button onClick={() => { setComponents(components + 1)}}>TestButton1</button>
        <button onClick={() => { setVar1(var1 + 1)}}>TestButton2</button>
    </div>
)

This way the components aren't wrapping around the value of var1 at the time they were created, and are instead dynamically created with the current value of var1.

Example

David
  • 208,112
  • 36
  • 198
  • 279