React: Calling a function from another component.

Created on 21 Apr 2017  路  2Comments  路  Source: facebook/react

Hi,

I need to call a method in a component from another component, how can I do that?

In the below code I need to call the toggle method from a different component onClick, I tried finding a solution but not successful. Any suggestions!!!

Thank you,

    class //extends React.Component {
        constructor() {
            super();
         //
        render() {
         //
            const toggle = () => {
              ///
                    });
                    return;
                }
                this.setState({
               //

                });
            };
            return (
              ////
            )
        }
    }

Most helpful comment

@yolohello12

A child can call a parent method by passing the method from the parent to the child as a prop:

class Parent extends React.Component {
  toggle = () => {
    // update state
  };
  render() {
    return <Child onClick={this.toggle} />;
  }
}

class Child extends React.Component {
  render() {
    // The parent's toggle method is available as this.props.onClick
    return <button onClick={this.props.onClick}>Toggle</button>;
  }
}

If you need to go the reverse direction and call a child's method from a parent, then refs are one option, but as @bvaughn said, try to avoid refs if you can. Try to use props for data flow whenever possible.

All 2 comments

The section of the docs called "Refs and the DOM" will probably be helpful for you.

We suggest you do as much as you can declaratively (through props) but if you need to call a method on an instance of another component, use a ref.

@yolohello12

A child can call a parent method by passing the method from the parent to the child as a prop:

class Parent extends React.Component {
  toggle = () => {
    // update state
  };
  render() {
    return <Child onClick={this.toggle} />;
  }
}

class Child extends React.Component {
  render() {
    // The parent's toggle method is available as this.props.onClick
    return <button onClick={this.props.onClick}>Toggle</button>;
  }
}

If you need to go the reverse direction and call a child's method from a parent, then refs are one option, but as @bvaughn said, try to avoid refs if you can. Try to use props for data flow whenever possible.

Was this page helpful?
0 / 5 - 0 ratings