1

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

2 Answers 2

1

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)});
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the explanation! Only now I noticed that my this.state.result does nothing
what do you mean this.state.result 'does nothing'?
0

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

2 Comments

Thank you so much!!
Your welcome. Please check the checkmark to the left of whichever answer helped you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.