Search code examples
meteorreactjsflow-router

( React.js ) Can I use a function thats placed in a different component?


I've got the mainComponent. Now Im rendering two different components based on 1>2, for example. Now How would can I use the data and function from a different component on another component

ComponentOne = React.createClass({
    render() {
        /* use theFunctionImTryingToRun  -output "a" */
    }
})



mainComponent = React.createClass({
      var x = ["a","b","c"];
   theFunctionImTryingToRun: function(){
        console.log(x[0]);

},
 mainRender: function(){
  if (1<2) {
    return (<ComponentOne /> );  
} else {
  return (<ComponentTwo />);
}

}

render() {
        return  <div> {this.mainRender()} </div>
    }
})

Solution

  • MainComponent

    var MainComponent = React.createClass({    
      theFunctionImTryingToRun: function() {
        var x = ["a","b","c"];
        console.log(x[0]);
      },
    
      render: function() {
        return 1 < 2 ?
          <ComponentOne myFunction={this.theFunctionImTryingToRun} /> :
          <ComponentTwo />;
      }  
    });
    

    ComponentOne

    var ComponentOne = React.createClass({   
        render: function() {
            this.props.myFunction();
            return <h1>Hello World</h1>;
        }
    });