How to call a component method from another component?

I have a header component that contains a button, and I want this button to display another component (modal page) when clicked.

Can I do something like this:

Here is my header component:

import ComponentToDisplay from './components/ComponentToDisplay/index' class Header extends React.Component { constructor(props) { super(props) } props : { user: User } _handleInvitePlayerClick = () => { this.refs.simpleDialog.show(); } render(){ return( <Button onClick={this._handleInvitePlayerClick} ><myButton/></Button> <ComponentToDisplay /> ) } } 

Here is my component for a modal page that should appear when a button is clicked on another component:

 class ComponentToDisplay extends React.Component { componentDidMount() { } render() { return ( <div> <SkyLight ref="simpleDialog" title={"Title for the modal"}> {"Text inside the modal."} <Button onClick={() => this.refs.simpleDialog.hide()}>{"Close modal"}</Button> </SkyLight> </div> ) } } 

The library is used for modal: https://github.com/marcio/react-skylight

+1
javascript reactjs
source share
1 answer

Moreover:

 class Header extends React.Component { constructor(props) { super(props) } props: { user: User } render() { return ( <Button onClick={() => this.refs.componentToDisplay.showMe()}><myButton /></Button> <ComponentToDisplay ref="componentToDisplay" /> ) } } 

Be sure to show the showMe() method for your child component:

 class ComponentToDisplay extends React.Component { showMe() { this.refs.simpleDialog.show(); } render() { return ( <div> <SkyLight ref="simpleDialog" title={"Title for the modal"}> {"Text inside the modal."} <Button onClick={() => this.refs.simpleDialog.hide()}>{"Close modal"}</Button> </SkyLight> </div> ) } } 

Basically, what happens here, you end the SkyLight show() method in the native method of the child component (in this case showMe() ). Then, in your parent component, you add a link to your child component so that you can reference it and call this method.

+1
source share

All Articles