Categories
Uncategorized

Lifting State Up in React.JS

Many times we want to reflect a change somewhere, if some change done. For example, if value is less than 100, display some text otherwise, if value is greater than 100, then display different text. It has been shown in following program:

1) First create a class of React. First of all it creates a constructor(), which includes initial state (this.state) of temperature to empty. And an event binding has been done for handleChange. In next, handleChange event has been coded to change the initial empty state of temperature to an value (e.target.value) which is entered by user. Finally, in this class, in render(), HTML coding has been done, for creating a fieldset, where onChange in any text in this field, handleChange() event made before will fetch the latest value entered. Same value written by user has been assigned to fieldset’s ‘value’ which is ‘this.state.temperature’. Inside fieldset, we have created a function ‘BoilingVerdict’ whose props ‘celsius’ has value of ‘temperature’ entered by user:

class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {temperature: ''};                                             

this.handleChange = this.handleChange.bind(this);
}

handleChange(e) {
this.setState({temperature: e.target.value});
}

render() {
const temperature = this.state.temperature;
return (
<fieldset>
<legend>Enter temperature in Celsius:</legend>
<input
value={temperature}
onChange={this.handleChange} />
<BoilingVerdict
celsius={parseFloat(temperature)} />
</fieldset>
);
}
}

2) BoilingVerdict function called in class above has been created below. What it does is, it fetch the value of props which is stored in ‘celsius’. If the value of ‘celsius’, entered by user, for temperature is more than 100, then return a message written in HTML, otherwise return other message written in HTML, in this function.

function BoilingVerdict(props) {
if (props.celsius >= 100) {
return <p>The water would boil.</p>;
}
return <p>The water would not boil.</p>;
}

3) In the end the class ‘Calculator’ output has been displayed in ReactDOM.

ReactDOM.render(
<Calculator />,
document.getElementById('root')
);

What it do is, if user enter a number less than 100, it shows message: The water would not boil.

If the user entered a number greater than or equal to 100, then it shows message: The water would boil.


This get more complex with new conditions added. For example, if we want to show temperature automatically changed from Celsius to Fahrenheit and vice-versa in two text boxes and also show a message if temperature is less than 100 Degree Celsius or more than it, then such a example can be seen here.

Leave a Reply

Your email address will not be published. Required fields are marked *