Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class CurrencyConverter extends Component {
state = {
isSwapped: false,
originCurrencyValue: 0,
destinationCurrencyValue: 0,
}
render() {
const { baseCurrency,quoteCurrency } = this.props
const { originCurrencyValue, destinationCurrencyValue, isSwapped} = this.state
return (
<div>
<div onClick={this.handleSwap}>Swap!</div>
<CurrencyConverterInput
currency={isSwapped ? quoteCurrency : baseCurrency}
value={originCurrencyValue}
onChange={(event) => this.handleChange(event, 'origin')}
/>
<CurrencyConverterInput
currency={isSwapped ? baseCurrency : quoteCurrency}
value={destinationCurrencyValue}
onChange={(event) => this.handleChange(event, 'destination')}
/>
</div>
);
}
handleSwap = () => {
const { originCurrencyValue, destinationCurrencyValue, isSwapped, lastModified } = this.state
this.setState({
isSwapped: !isSwapped
}, () => {
const value = lastModified === 'origin' ? originCurrencyValue : destinationCurrencyValue
this.handleChange({target: {value}}, lastModified)
})
}
handleChange = (event, type) => {
const { isSwapped } = this.state
const value = event.target.value
const opositeType = this.getOpositeType(type)
this.setState({
lastModified: type,
[`${type}CurrencyValue`]: value,
[`${opositeType}CurrencyValue`]: this.calculateCurrencyValue(value, isSwapped, opositeType),
})
}
calculateCurrencyValue = (opositeValue, isSwapped, type) => {
const { exchangeRate } = this.props
const opositeType = this.getOpositeType(type)
const finalType = isSwapped ? opositeType : type
if(finalType === 'origin') return opositeValue / exchangeRate
return opositeValue * exchangeRate
}
getOpositeType = type => type === 'origin' ? 'destination' : 'origin'
}
const CurrencyConverterInput = ({ value, onChange, currency }) => {
return (
<div>
<label>{currency.name}</label>
<input type="number" step="0.01" value={value} onChange={onChange}/>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.