Richard
Richard

Reputation: 1117

Handling Parent function call in Child in React

Is it possible to create a method in Parent class in React and then pass it on to the Child and use it there.

So basically I would create a button in my Parent class, pass the function on to the Child and when the Button is clicked, the child will know about it and Parent will not really care for it?

class App extends Component {
  clickMade = () => {
    //This should be left empty
  };

  render() {
    return (
      <div className="App">
        <Button onClick={this.clickMade}>Click me </Button>
        <Child clickMade={this.clickMade} />
      </div>
    );
  }
}

export default App;

And the Child:

class Child extends Component {

  constructor(props) {
    super(props);

    this.handleClick = this.props.clickMade.bind(this);
  }

  handleClick = () => {
    console.log("Click in child");
  }

  render() {
    return null;
  }
}

export default Child;

And a sandbox for this: CodeSandbox

Upvotes: 1

Views: 38

Answers (1)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

App.js

class App extends Component {

  clickMade = () => {
    this.childRef.handleClick();
  };

  render() {
    return (
      <div className="App">
        <Button onClick={this.clickMade}>Click me </Button>
        <Child
          ref={ref => {
           this.childRef = ref;
          }}
        />
      </div>
    );
  }
}

Upvotes: 1

Related Questions