Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a basic form calculator with React js

To create an HTML form with dynamic calculations and updates, say just two inputs that are to be multiplied together and with the product presented in text below, what would the basic structure look like. i.e. which data would be kept in state? Should any react mixins be used?

Thank you!

like image 883
user4815162342 Avatar asked Nov 21 '25 00:11

user4815162342


1 Answers

This component should hold the product of the two numbers as state. You can hold the values of the two numbers within the DOM, since you have your form.

You would need an html form in the render of the react component. The render might look something like this:

render: function() {
   var product = '';
   if (this.state.product) {
     product = <p>{this.state.product}</p>;
   }
   return (
   <div>
    {product}
    <form onSubmit={this.submit}>
      <input type="text" ref="num1" className="form-control" placeholder="First number"></input>
      <input type="text" ref="num2" className="form-control" placeholder="Second number"></input>
      <button type="submit" className="btn btn-danger">Delete</button>
      <button type="reset" className="btn btn-default">Cancel</button>
    </form>
   </div>
  );
},

Then, you need a function on your react class called submit() that gets the form values like this:

var num1 = this.refs.num1.getDOMNode().value.trim();
var num2 = this.refs.num2.getDOMNode().value.trim();

And then you should just multiply them and store them as state:

this.setState({ product: num1 * num2 });

Make sure you use getInitialState() and initialize the product to null:

getInitialState: function() {
  return { product: null };
},
like image 61
ritmatter Avatar answered Nov 22 '25 13:11

ritmatter