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!
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 };
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With