I'm trying to switch from using Class Components to Function Components and hooks in ReactJS. I have created a simple program to illustrate what I am trying to do.
This is a child component, which has a name and a value:
function Child(props) {
const [value, setValue] = useState(0)
function increment() { setValue(value 1) }
return (<div>Child ({props.name}): {value}</div>)
}
The child component would be passed to a parent, which has its own value, and when this value is decremented, the value of the child should increment:
function Parent(props) {
const [value, setValue] = useState(10)
function decrement() { setValue(value - 1) }
return (<div>
<div>Parent: {value}</div>
<button onClick={decrement}>Pass from parent to child</button>
{props.child}
</div>)
}
The child is passed to the parent the application level (in theory, children can be switched dynamically, but to simplify here we set one of two):
function Application(props) {
const child1 = <Child name="Alice" />
const child2 = <Child name="Bob" />
const child = props.option == "Alice" ? child1 : child2
return (<Parent child={child} />)
}
Now what I need here is that when the parent's value is decremented, the child's value should increment. In React, you don't directly call a child component's method from the parent, so I am looking for a way to achieve this that will also allow me to change the child component as shown in the code.
If you run the code pen below this will make sense.
CodePudding user response:
Here is the solution you are looking for
const { useState } = React;
function Parent(props) {
const [value, setValue] = useState(10)
const [childValue, setChildValue] = useState(0)
function changeValue(){
setValue(value-1);
setChildValue(childValue 1);
}
return (<div>
<div>Parent: {value}</div>
<button onClick={changeValue}>Pass from parent to child</button>
<Child name={props.option} value={childValue} />
</div>)
}
function Child(props) {
return (<div>Child ({props.name}): {props.value}</div>)
}
function Application(props) {
// Child component is decided by the Application component and can change at any time
return (<Parent option={props.option} />)
}
Instead of passing child component from application component pass from Parent component.
I hope this is what you are looking for.