Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  104] [ 5]  / answers: 1 / hits: 16750  / 11 Years ago, fri, january 10, 2014, 12:00:00

I'm trying to get a button rendered through another component to reference and/or influence the state of a different 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 will be able to access the add function in Inputs. I tried to reference it directly with Inputs.add like this:



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


But that didn't work. How would I be able to access a component's functions through another component, or influence the state of a component through another component? Thanks.


More From » reactjs

 Answers
2

You could accomplish this by creating a parent component that is responsible for managing the state and then just push the state down to the sub-components 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


[#73252] Thursday, January 9, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trentb

Total Points: 261
Total Questions: 101
Total Answers: 90

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
trentb questions
Sat, Mar 27, 21, 00:00, 3 Years ago
Fri, Feb 26, 21, 00:00, 3 Years ago
Thu, Sep 24, 20, 00:00, 4 Years ago
;