0

Could you tell me please, how can I duplicate the values of the states value from the child component Child to parent Parent. The child component implements the increment and decrement of the state on the buttons. The value should also be displayed in Parent. Thanks!

import React, {useState} from 'react';
import Child from "./Child";

const Parent = () => {
    const [value, setValue] = useState(0);
    return (
        <>
            <span>{value}</span>
            <Child data={value} />
        </>
    );
}
export default Parent;
import React, {useState} from 'react';

const Child = ({data}) => {
    const [value, setValue] = useState(data);

    const increment = () => {
        setValue(prevState => prevState + 1)
    };

    const decrement = () => {
        setValue(prevState => prevState - 1)
    };

    return (
        <>
            <button onClick={increment}>+</button>
            <span>{value}</span>
            <button onClick={decrement}>-</button>
        </>
    );
};
export default Child;
Propool
  • 25
  • 4

2 Answers2

0

The easiest way is to define the state in the parent component and then pass the value and the setValue as props to the child component.

<Child value={value} setValue={setValue} />

Then you just call the setValue from the props object to set the state.

PRSHL
  • 1,359
  • 1
  • 11
  • 30
0

You can do this by either passing down a method from the parent to child as a prop or you can manage the state outside using redux. Furthermore, follow this discussion to get a better understanding.

Harsh Gaur
  • 39
  • 2