Consider the following code block :
class FormInputComponent extends React.Component {
render() {
return (<input type="text" value={this.props.valueHandler} onChange={this.props.changeHandler} />);
}
}
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
rate: 50,
inputOne: 0,
inputTwo: 0
}
}
changeHandler(key) {
switch(key) {
case "ONE":
this.setState({
inputOne: event.target.value
});
break;
case "TWO":
this.setState({
inputTwo: event.target.value
});
break;
}
}
getValue(key) {
switch(key) {
case "ONE":
return this.state.inputOne;
break;
case "TWO":
return this.state.inputTwo;
break;
}
}
render() {
return (
<div>
<FormInputComponent valueHandler={this.getValue("ONE")} changeHandler={this.changeHandler.bind(this, "ONE")} />
<br />
<FormInputComponent valueHandler={this.getValue("TWO")} changeHandler={this.changeHandler.bind(this, "TWO")}/>
</div>);
}
}
ReactDOM.render(<MyApp />, document.body);
At the moment, the two input field components get their value props from whatever the user keys in the respective fields (Controlled). Here's the functionality that I want :
When the user types a value in the first input field (e.g. 30), then the second input field should instantly update with the value 30 * this.state.rate i.e. the second field should show 1500.
Next, if the user types a value in the second input field, or even edits it, the first input field should show a resulting value computed as (val/this.state.rate). So, if someone types 3500 in the second field, the resulting value (3500/50) should be shown in the first input field.
This can be achieved by computing the resulting values and storing them in two state variables. In this case, the two form field components can simply output the values of the state variables.
As per React docs, computed values should not be ideally stored in state and should be rather computed in the render method. However, in this case, how would we achieve the result without storing computed values in the state??
Here's a link to the JSBIN for the above code : https://jsbin.com/poxuqe/edit?js,console,output