Open modal from another component click in react js

pj013 picture pj013 · Oct 15, 2017 · Viewed 11.4k times · Source

I am using the basic component modal component of react - https://github.com/reactjs/react-modal

What I am trying to achieve is that I want to open the modal from another parent that has the modal imported.

Parent.js
<button onClick={() => this.refs.setState({modalIsOpen: true})}> - THIS BUTTON ELEMENT IS IN ANOTHER COMPONENT

Modal.js
import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';

const customStyles = {
content : {
top                   : '50%',
left                  : '50%',
right                 : 'auto',
bottom                : 'auto',
marginRight           : '-50%',
transform             : 'translate(-50%, -50%)'
}
};

class App extends React.Component {
 constructor() {
 super();

 this.state = {
  modalIsOpen: false
 };

 this.openModal = this.openModal.bind(this);
 this.afterOpenModal = this.afterOpenModal.bind(this);
 this.closeModal = this.closeModal.bind(this);
}

openModal() {
 this.setState({modalIsOpen: true});
}

afterOpenModal() {
 // references are now sync'd and can be accessed.
 this.subtitle.style.color = '#f00';
 }

closeModal() {
 this.setState({modalIsOpen: false});
}

render() {
 return (
  <div>
    <button onClick={this.openModal}>Open Modal</button>
    <Modal
      isOpen={this.state.modalIsOpen}
      onAfterOpen={this.afterOpenModal}
      onRequestClose={this.closeModal}
      style={customStyles}
      contentLabel="Example Modal"
    >

      <h2 ref={subtitle => this.subtitle = subtitle}>Hello</h2>
      <button onClick={this.closeModal}>close</button>
      <div>I am a modal</div>
      <form>
        <input />
        <button>tab navigation</button>
        <button>stays</button>
        <button>inside</button>
        <button>the modal</button>
      </form>
    </Modal>
  </div>
);
}
}

export default App

I have read that this can be done using refs and changing the state of the modal. What exactly am I doing wrong here?

Thanks!

Answer

Ferhat BAŞ picture Ferhat BAŞ · Oct 15, 2017

Can you try below code in parent

<button onClick={() => this._modal.openModal()}>click</button>

when you call your modal component use ref attribute then can call like above code.

<Modal ref={(modal) => { this._modal = modal; }} />