Skip to content

Instantly share code, notes, and snippets.

@gt3
Last active March 8, 2017 20:20
Show Gist options
  • Save gt3/c143face12b65ff50e145f90485b9de2 to your computer and use it in GitHub Desktop.
Save gt3/c143face12b65ff50e145f90485b9de2 to your computer and use it in GitHub Desktop.
Temperature Calculator from React official docs
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>
)
}
}
@gt3
Copy link
Author

gt3 commented Mar 8, 2017

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