Reputation: 155
In my React component, it renders a child component. React instantiants an object of ChildComponent when it renders.
My question is how can I force react to reinstantiants an object of when I click a button in Parent Component? I want the ChildComponent to be 'reset', i.e. like when it is newly called the constructor.
export class ParentComponent extends React.Component {
private handleButtonClick() {
// re-instantiate ChildComponent
}
public render() {
return (
<Button onClick={handleButtonClick}/>
<ChildComponent />
)
}
Upvotes: 0
Views: 1105
Reputation: 3290
If you want to re-render, just update some state. If you want to call the constructor of children, then update some state and pass it as key={someState}.
state = {
someState: true
}
private handleButtonClick() {
// just update someState
this.setState((oldState) => ({someState: !oldState.someState}))
}
public render() {
return (
<>
<Button onClick={handleButtonClick}/>
<ChildComponent key={String(someState)} />
</>
)
}
Upvotes: 0
Reputation: 473
You can create a hook or state variable and add as a property of ChildComponent. And in the handleButtonClick callback function, you need to change the value of the variable and your ChildComponent will be re-render
Upvotes: 0