M
M
Maxim Kalinin2020-10-07 20:44:24
React
Maxim Kalinin, 2020-10-07 20:44:24

How to change parent state from child React component?

I pass the state of the parent to the child component: Next, in the child component, there is an element on click on which a method is called that should change the state of the parent to true. How to do it? <Component openModal={this.state.openModal} />

Answer the question

In order to leave comments, you need to log in

4 answer(s)
8
8XL, 2020-10-07
@MaximAr1es

The correct solution was suggested, I will disassemble it a little for understanding.

<Parent>
  <Children openModal={this.state.openModal} onChange={this.onChange} />
<Parent />

in Parent declare a method
onChange=()=>{
  this.setState({openModal : true})
}

In Children so
<div onClick={this.props.onChange}>
  ...какие-то элементы...
</div>

It's simple)
But even simpler and much more reliable https://ru.reactjs.org/docs/lifting-state-up.html

M
Michael, 2020-10-07
@notiv-nt

<Component openModal={this.state.openModal} onChange={this.onChange} />

G
Gary_Ihar, 2020-10-07
@Gary_Ihar

1) create a handler in the parent component that will change the state.
2) pass the handler to the child component.
3) use the handler in the child component and change the State in the parent component.

K
Kirill Makarov, 2020-10-07
@kirbi1996

In addition to the state, also throw a function from the parent there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question