Last active
March 8, 2017 20:20
-
-
Save gt3/c143face12b65ff50e145f90485b9de2 to your computer and use it in GitHub Desktop.
Temperature Calculator from React official docs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { scaleNames, TemperatureInput, BoilingVerdict } from './presentation.jsx' | |
function toCelsius(fahrenheit) { | |
return (fahrenheit - 32) * 5 / 9 | |
} | |
function toFahrenheit(celsius) { | |
return (celsius * 9 / 5) + 32 | |
} | |
function tryConvert(value, convert) { | |
const input = parseFloat(value) | |
if (Number.isNaN(input)) return '' | |
const output = convert(input) | |
const rounded = Math.round(output * 1000) / 1000 | |
return rounded.toString() | |
} | |
class Calculator extends React.Component { | |
constructor(props) { | |
super(props) | |
this.handleCelsiusChange = this.handleCelsiusChange.bind(this) | |
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this) | |
this.state = { value: '', scale: 'c' } | |
} | |
handleCelsiusChange(value) { | |
this.setState({ scale: 'c', value }) | |
} | |
handleFahrenheitChange(value) { | |
this.setState({ scale: 'f', value }) | |
} | |
render() { | |
const scale = this.state.scale | |
const value = this.state.value | |
const celsius = scale === 'f' ? tryConvert(value, toCelsius) : value | |
const fahrenheit = scale === 'c' ? tryConvert(value, toFahrenheit) : value | |
return ( | |
<div> | |
<TemperatureInput scale="c" value={celsius} onChange={this.handleCelsiusChange} /> | |
<TemperatureInput scale="f" value={fahrenheit} onChange={this.handleFahrenheitChange} /> | |
<BoilingVerdict celsius={parseFloat(celsius)} /> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
React official example: https://facebook.github.io/react/docs/lifting-state-up.html