Reputation: 239
I'm trying to get the value of input onClick(not onChange) and I got really confused. (the function should take user input and multiply it by 5)
var Multiply = React.createClass({
getInitialState: function(){
return {number: '-'}
},
multiply: function(a){
return (a * 5);
},
handleChange: function(e) {
this.setState({ number: e.target.value });
},
handleClick: function(e) {
this.multiply(this.state.number);
},
render: function () {
return (
<div>
<p>multiply by 5!</p><br />
<textarea onChange={this.handleChange}>
</textarea><br/>
<button onClick={this.handleClick}>Submit</button>
<p>result:</p> {this.state.result}
</div>
);
}
});
ReactDOM.render(
<Multiply/>,
document.getElementById('root')
);
Here is a link to code: http://codepen.io/polinaz/pen/MmezZy?editors=0010
What's wrong with my logic? Will really appreciate a good explanation! Thank you
Upvotes: 1
Views: 9158
Reputation: 2302
I added result to the state, and added a result variable into the multiply function so you can store it in the state. Please look below:
var Multiply = React.createClass({
getInitialState: function(){
//added result to the initial state here
return {number: '-',
result: 0}
},
multiply: function(a){
//added result var here, and set the state to accept this result
var result = a * 5;
this.setState({result: result});
},
handleChange: function(e) {
this.setState({ number: e.target.value });
},
handleClick: function(e) {
this.multiply(this.state.number);
},
render: function () {
return (
<div>
<p>multiply by 5!</p><br />
<textarea onChange={this.handleChange}>
</textarea><br/>
<button onClick={this.handleClick}>Submit</button>
<p>result:</p> {this.state.result}
</div>
);
}
});
ReactDOM.render(
<Multiply/>,
document.getElementById('root')
);
Upvotes: 0
Reputation: 9073
When you click the button, it multiples the number by 5, but then you don't do anything with that multiplied number (the result). In your handleClick function you need something like this:
handleClick: function(e) {
this.setState({result: this.multiply(this.state.number)});
}
Upvotes: 1