Linked Questions

Popular Questions

I am trying to get data from parent component. I know that I can pass in functions or variables to the child component but its looks cleaner to just pass in this to child component to access to its parent functions or variables.

class Parent extends Component {
  state = {
    _id: 123456789
  }

  foo = (val) => {
    this.setState({_id:val})
  }

  render() {
    return(
      <Child parentInstance={this} />
    )
  }
}

class Child extends Component {
  update = (e) => {
    this.props.parentInstance.foo(e.target.value);
  }

  render() {
    return(
      <p>{this.props.parentInstance.state._id}</p>
      <input onChange={this.update} />
    )
  }
}

Related Questions