Michele La Corte
Michele La Corte

Reputation: 21

Is it possible to pass the Parent instance to a Child compontent into props attributes?

I am passing the whole Parent instance to the Child in the props like this:

var Parent = React.createClass({
  render() {
      return <Child parent={this} />;
  },
doAThing() {
    console.log("Doing A Thing!");
  }
});

var Child = React.createClass({
  render() {
    return <button onClick={this.onClick}>Do A Thing...</button>
  },

  onClick() {
    let parent = this.props.parent
    parent.doAThing();
  }
});

It works fine, i just wonder if is good practice or if i should avoid it.

Upvotes: 1

Views: 27

Answers (1)

Estus Flask
Estus Flask

Reputation: 222840

This is not a good practice because a child shouldn't be aware of parent's implementation, according to the principle of least privilege. When a child is supposed to do something, it should be provided with a callback:

<Child onClick={() => this.doAThing()} />;

And it can use a prop directly:

<button onClick={this.props.onClick}>

Upvotes: 3

Related Questions