4

I have a modal component with two methods that show/hide the modal. How can I call those methods from another component?

This is the code for the Modal:

// Dependencies
//==============================================================================
import React from 'react'
import Modal from 'boron/DropModal'

// Class definition
//==============================================================================
export default class RegistrationModal extends React.Component {
  showRegistrationModal() {
    this.refs.registrationModal.show()
  }

  hideRegistrationModal() {
    this.refs.registrationModal.hide()
  }

  render() {
    return (
      <Modal ref="registrationModal" className="modal">
        <h2>Meld je aan</h2>
        <button onClick={this.hideRegistrationModal.bind(this)}>Close</button>
      </Modal>
    )
  }
}
noodles_ftw
  • 1,293
  • 1
  • 9
  • 17

3 Answers3

1

You can call a components method from the outside as long as you keep a reference to the component. For example:

let myRegistrationModal = ReactDOM.render(<RegistrationModal />, approot );
    // now you can call the method:
    myRegistrationModal.showRegistrationModal() 

It's a bit cleaner if you pass a reference to the modal to another component, like a button:

let OpenModalButton = props => (
  <button onClick={ props.modal.showRegistrationModal }>{ props.children }</button>
);
let myRegistrationModal = ReactDOM.render(<RegistrationModal />, modalContainer );

ReactDOM.render(<OpenModalButton modal={ myRegistrationModal }>Click to open</OpenModalButton>, buttonContainer );

Working example: http://jsfiddle.net/69z2wepo/48169/

pawel
  • 35,827
  • 7
  • 56
  • 53
0

You cant call it from another component, because its a method belong to RegistrationModal component, but you can refactor your code so you can call it

export function hideRegistrationModal() {
  console.log("ok");
}

export default class RegistrationModal extends React.Component {
  render() {
    return (
      <Modal ref="registrationModal" className="modal">
        <h2>Meld je aan</h2>
        <button onClick={hideRegistrationModal}>Close</button>
      </Modal>
    )
  }
}

now you can call from anywhere but you need to import it first like this

import { RegistrationModal, hideRegistrationModal } from 'path to modal.js'
//       ^-- Component name  ^-- Method
elreeda
  • 4,525
  • 2
  • 18
  • 45
  • Doing a `console.log` seems to work, but how would I access the `registrationModal` ref in the `RegistrationModal` class? – noodles_ftw Jul 07 '16 at 12:06
0

What you want to do is create a parent component which will handle the communication between your modals.

A really great example and explanation can be found here: ReactJS Two components communicating

This is a good approach because it keeps your components decoupled.

Community
  • 1
  • 1
Dennis
  • 3,962
  • 7
  • 26
  • 44