React JS reference function in another component

I am trying to get a button passed by another component to refer and / or influence the state of another component.

var Inputs = React.createClass({ getInitialState: function(){ return {count: 1}; }, add: function(){ this.setState({ count: this.state.count + 1 }); }, render: function(){ var items = []; var inputs; for (var i = 0; i < this.state.count; i++){ items.push(<input type="text" name={[i]} />); items.push(<br />); } return ( <div className="col-md-9"> <form action="/" method="post" name="form1"> {items} <input type="submit" className="btn btn-success" value="Submit Form" /> </form> </div> ); } }); 

I want to write a new component that can access the add function in Inputs. I tried to reference it directly using Inputs.add as follows:

 var Add = React.createClass({ render: function(){ return ( <input type="button" className="btn" value="Add an Input" onClick={Inputs.add} /> ); } }); 

But that did not work. How can I access components through another component or affect the state of a component through another component? Thanks.

+7
javascript reactjs
source share
2 answers

This can be done by creating a parent component that is responsible for managing the state, and then just pushing it to the subcomponents as props.

 /** @jsx React.DOM */ var Inputs = React.createClass({ render: function () { var items = []; var inputs; for (var i = 0; i < this.props.count; i++) { items.push( <input type="text" name={[i]} />); items.push(<br />); } return ( <div className = "col-md-9"> <form action = "/" method = "post" name = "form1"> {items} <input type="submit" className="btn btn-success" value = "Submit Form" /> </form> </div> ); } }); var Add = React.createClass({ render: function () { return (<input type = "button" className="btn" value="Add an Input" onClick={this.props.fnClick}/> ); } }); var Parent = React.createClass({ getInitialState: function(){ return {count:1} }, addInput: function(){ var newCount = this.state.count + 1; this.setState({count: newCount}); }, render: function(){ return ( <div> <Inputs count={this.state.count}></Inputs> <Add fnClick={this.addInput}/> </div> ); } }); React.renderComponent(<Parent></Parent> , document.body); 

jsFiddle

+9
source share

You can call functions on the return value of renderComponent :

 var Inputs = React.createClass({…}); var myInputs = React.renderComponent(Inputs); myInputs.add(); 

The only way to get the React Component instance handle outside of React is to store the return value of the React.renderComponent. Source

+1
source share

All Articles