Skip to content Skip to sidebar Skip to footer

React Js Call Function Within Another Component

I'm trying to call one function from another component in React with the Mousetrap library. class Parent extends React.Component { constructor() { super(); } ..

Solution 1:

It would be better to have that be part of your state, e.g.

classParentextendsReact.Component {
  constructor(){
    super();
    this._eKeyPress = this._eKeyPress.bind(this);
    this.state.showChild = false;
  }
  componentDidMount(){
    Mousetrap.bind('e', this._eKeyPress);
  }
  componentWillUnmount(){
    Mousetrap.unbind('e', this._eKeyPress);
  }
  _eKeyPress(){
    this.setState({showChild: true});
  }

  render(){
    return<Childshow={this.state.showChild} />;
  }
}

The next question after that is whether you need to create the child at all, since you could also do

render(){
  returnthis.state.showChild ? <Child /> : null;
}

Post a Comment for "React Js Call Function Within Another Component"