Search code examples
reactjsevent-handlingmodal-dialogreact-propsreact-ref

Call a component method from another component with ref


I'm trying to call a show method of my Modal component when the user clicks the <button> in the App component, but it doesn't work.

I use a ref to access the Modal component from the App component.

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.show = this.show.bind(this);
  }

  show() {
    console.log('show');
  }

  render() {
    return (
      <div>...</div>
    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);
    this.modalRef = React.createRef();
  }

  render() {
    return (
      <div>
        <Modal ref={this.modalRef}/>

        <button id="myBtn" onClick={ this.modalRef.show }>
          Call show modal method
        </button>
      </div>
    );
  }
}

Solution

  • I Tried with the regular ref approach and it seems be working with all your existing code

    class Modal extends React.Component {
      show = () => {
        console.log("show");
      };
    
      render() {
        return <div />;
      }
    }
    
    class App extends Component {
      render() {
        return (
          <div>
            <Modal ref={ref => (this._modal = ref)} />
            <button id="myBtn" onClick={() => this._modal.show()}>
              call show modal method
            </button>
          </div>
        );
      }
    }
    

    Demo Link: https://codesandbox.io/s/react-example-z893s?file=/index.js:77-461

    Let me know if this helps!