Skip to content

Instantly share code, notes, and snippets.

@react-ram
Created July 24, 2019 09:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save react-ram/a57a3929c41ad44faf1f3bf009ca8495 to your computer and use it in GitHub Desktop.
Save react-ram/a57a3929c41ad44faf1f3bf009ca8495 to your computer and use it in GitHub Desktop.
Example: Lifting the state up
import React, { Component } from "react";
import "./App.css";
import Calculator from "./Calculator";
export class App extends Component {
render() {
return (
<div className="App">
<Calculator />
</div>
);
}
}
export default App;
import React, { Component } from "react";
import TemperatureInput from "./TemperatureInput";
class Calculator extends Component {
constructor(props) {
super(props);
this.state = {
temperature: "",
scale: ""
};
}
handleCelsiusChange = temperature => {
this.setState({ scale: "c", temperature });
};
handleFahrenheitChange = temperature => {
this.setState({ scale: "f", temperature });
};
toCelsius = fahrenheit => {
return ((fahrenheit - 32) * 5) / 9;
};
toFahrenheit = celsius => {
return (celsius * 9) / 5 + 32;
};
tryConvert = (temperature, convert) => {
const input = parseFloat(temperature);
if (Number.isNaN(input)) {
return "";
}
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
};
render() {
const { temperature, scale } = this.state;
const celsius =
scale === "f"
? this.tryConvert(temperature, this.toCelsius)
: temperature;
const fahrenheit =
scale === "c"
? this.tryConvert(temperature, this.toFahrenheit)
: temperature;
return (
<div>
<TemperatureInput
temperature={celsius}
onTempChange={this.handleCelsiusChange}
scale={"c"}
/>
<TemperatureInput
temperature={fahrenheit}
onTempChange={this.handleFahrenheitChange}
scale={"f"}
/>
</div>
);
}
}
export default Calculator;
import React, { Component } from "react";
const scaleNames = {
c: "celsius",
f: "fahrenheit"
};
class TemperatureInput extends Component {
handleTemperature = event => {
//this.setState({ temperature: event.target.value });
this.props.onTempChange(event.target.value);
};
render() {
const { scale, temperature } = this.props;
return (
<fieldset>
<legend>enter temperature in {scaleNames[scale]} </legend>
<input onChange={this.handleTemperature} value={temperature} />
</fieldset>
);
}
}
export default TemperatureInput;
@react-ram
Copy link
Author

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment