javascriptreactjsmousetrap

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();

    } 
    ...
    render() {
      return(...);
    }
}
class Child extends React.Component {
    constructor() {
      super();
      this.state = { show: false };
      this.open = this.open.bind(this);
      this.close = this.close.bind(this);
    }
    open() {
      this.setState({ show: true });
    }
    close() {
      this.setState({ show: true });
    }
    render() {
      return(...);
    }
}

Now, what I want to do is call Mousetrap.bind('e', function(e) { Child.open() }); somewhere in the parent (because the parent will be rendered, and the child will only be rendered on this command). But, I'm not sure where to actually include that. Would it be better to call that in the constructor, or somewhere in render(), or somewhere else I haven't considered?


Solution

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

    class Parent extends React.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 <Child show={this.state.showChild} />;
      }
    }
    

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

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