I was reading about "Lifting State Up" in React JS documentation and there is something I am not very clear about. The codepen can be found here: https://codepen.io/valscion/pen/jBNjja?editors=0010
In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange, but the latter contains a parameter of temperature. How are we passing this parameter? There is no argument passed in the onTemperatureChange. What am I missing here?
Hope someone can help me understand this.
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}
render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
);
}
}
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = {temperature: '', scale: 'c'};
}
handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature});
}
handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}
render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
return (
<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={this.handleCelsiusChange} />
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
);
}
}
Let's look at the TemperatureInput component first. When its input element fires a change event, this is handled by handleChange(e) (declared within the TemperatureInput component). You'll notice that it then calls this.props.onTemperatureChange with the parameter e.target.value (this is the value attribute of the input element).
Where does this.props.onTemperatureChange come from? It's set by the parent component Calculator that instantiates it. Looking at the render method of the Calculator component, you'll notice that the onTemperatureChange prop for each TemperatureInput instance is set to this.handle[Cel/Far]Change (both methods declared within the Calculator component).
So when the TemperatureInput component calls this.props.onTemperatureChange, it is in fact calling the handle[Cel/Far]Change method of the Calculator component.
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