Parent / Child props challange


(Saša Fišter) #1

Hi guys. I’m working on little side project, but I stucked so I need you help.

I have parent and child class. Problem is that i’ve put child component into parent, but child component have input field which data I need on parent (post request to server). I know that ReactJS’s workflow is in one direction, so I don’t want to push data back to parent. What is best solution for this?

Here is parent

https://gist.github.com/sasafister/5065a0781475051369cbd5a2b2c0e9e4

And here is child

https://gist.github.com/sasafister/d13dd3b027b5681bf8f70284e6a22465

Hope that you can


(Leone) #2

So, by that, you mean use callbacks as prop of the child? Like,

<Child onUpdateData={newData => updateData(newData)} />

(Joe312341) #3

You handle this in React by passing a function down to the child which the child can then call to update the state in the parent.

You can also decide to have the state in the parent only and change it directly (which the example below shows)

 class Parent extends React.Component {
    constructor(props){
      super(props)
      this.state = {
        price: 0
      }
      this.changePrice = this.changePrice.bind(this)
    }
    changePrice(newPrice){
      this.setState({price: newPrice})
    }
    render(){
      return (
        <Child changePrice={this.changePrice} price={price} />
      )
    }
 }

Then in the child component

class Child extends React.Component = {
  constructor(props){
    super(props)
  }
  this.handlePriceChange = this.handlePriceChange.bind(this)
  handlePriceChange(event){
    // here we change the value in the parent
    this.props.changePrice(event.target.value)
  }
  render(){
    // we use the parent value for the price
    <input onChange={this.handlePriceChange} value={this.props.price} />
  }
}

I didnt test this code, but it should work :slight_smile:


(Saša Fišter) #4

Thank you Joe, it works. Got it, only thing is you have to define state in this line

    <Child changePrice={this.changePrice} price={price} />

    <Child changePrice={this.changePrice} price={this.state.price} />