Created
May 31, 2019 22:03
-
-
Save kaueburiti/2496bfd94222622036bc53e30307faf0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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