Last active
May 27, 2024 11:59
-
-
Save nifrasismail/4c84e1ddbd51134aad1d1e7cc6675908 to your computer and use it in GitHub Desktop.
React Currency Converter - Simple Way
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 { useRef, useState } from "react"; | |
function SimpleCurrency () { | |
const [convertedValue, setConvertedValue] = useState(0); | |
const rates = [ | |
{ | |
from: 'USD', | |
to: 'LKR', | |
rate: 297 | |
}, | |
{ | |
from: 'SAR', | |
to: 'LKR', | |
rate: 85 | |
} | |
]; | |
const fromRef = useRef() | |
const toRef = useRef() | |
const amountRef = useRef() | |
const handleConvert = () => { | |
const fromCurrency = fromRef.current.value; | |
const toCurrency = toRef.current.value; | |
const amount = amountRef.current.value; | |
const convertionRate = rates.filter(({ from, to }) => from == fromCurrency && to == toCurrency); | |
const convertedValue = convertionRate[0]?.rate * amount; | |
setConvertedValue(convertedValue) | |
} | |
return ( | |
<> | |
<label>From</label> | |
<input ref={fromRef} name="from" type="text" /> | |
<label>To</label> | |
<input ref={toRef} name="to" type="text" /> | |
<label>Amount</label> | |
<input ref={amountRef} type="text" /> | |
<button onClick={handleConvert}>Convert</button> | |
{ | |
convertedValue > 0 && <h1>{convertedValue} {toRef.current.value.toUpperCase()}</h1> | |
} | |
</> | |
) | |
} | |
export default SimpleCurrency; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment