Search code examples
reactjsreact-rails

Trigger an action in another component through their parent in React


There are two components which has a parent, I would like to trigger one action in another component through their parent. So far I have tried this:

_mevent_show.js.jsx (One of the component):

gotoSearchPage() {
  this.props.gotoSearchPage()
},

return (
  <i className="fas fa-search"
      onClick={this.gotoSearchPage}>
  </i> )

_body.js.jsx (Parent)

gotoSearchPage() {
   this.calendar.changePropertyInCalendar()
},

render () {
  <Calendar mevents={this.state.mevents} ref={calendar => this.calendar = calendar}>
}

_calendar.js.jsx (The other component whose action should be triggered)

changePropertyInCalendar() {
  this.setState({searchPage: true})
},

These codes produce an error like this.calendar is null. I am using react-rails gem. Any suggestion? Thanks


Solution

  • I looks like your parent component (_body) is not controlling the state, as i can see the _calendar component is handling the state but it is the children and the parent component isn't able to access the state. So you have to structure your app as the parent is the responsible and the only one that can update the 'state' of your UI, also this will distribute the values through props or context.