T
T
testkeyc2020-01-27 14:32:14
React
testkeyc, 2020-01-27 14:32:14

How to pass state as props?

There are two files App and App2. How to pass state from one file to another as props b to display it on the page?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor Zhivagin, 2020-01-27
@Krasnodar_etc

Well, in the parent component, render the second component, throw props to it. What doesn't work?

H
hzzzzl, 2020-01-27
@hzzzzl

class Parent extends React.Component {
  state = { c2: null }

  comp2state = state => { this.setState({ c2: state }) }

  return (
    <>
      <ComponentOne c2state={this.state.c2} />
      <ComponentTwo onStateChange={this.comp2state} />
    </>
  )
}


class ComponentTwo extends React.Component {
  state = { bla: '' }

  onChange = e => {
    this.setState(
      { bla: e.target.value }, 
      () => this.props.onStateChange(this.state)
    )
  }

  return (
    <input value={this.state.bla} onChange={onChange} />
  )
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question