Tell us what’s happening:
I can’t get both of these conditions to pass. They appear mutually exclusive
- Changing the value of the second select element should not cause the converted amounts to be recalculated.
- Changing the value of the second select element should display the new converted amount and currency.
Your code so far
<!-- file: index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Currency Converter</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.26.5/babel.min.js"></script>
<script
data-plugins="transform-modules-umd"
type="text/babel"
src="index.jsx"
></script>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="root"></div>
<script
data-plugins="transform-modules-umd"
type="text/babel"
data-presets="react"
data-type="module"
>
import { CurrencyConverter } from './index.jsx';
ReactDOM.createRoot(document.getElementById('root')).render(<CurrencyConverter />);
</script>
</body>
</html>
/* file: index.jsx */
const { useState, useMemo, useEffect } = React;
export function CurrencyConverter() {
const [fromCurrency, setFromCurrency] = useState("USD");
const [toCurrency, setToCurrency] = useState("USD");
const [amount, setAmount] = useState(1)
const moneyMap = {
USD: 1,
EUR: 0.92,
GBP: 0.78,
JPY: 156.7
};
const converted = useMemo(() => {
if (!amount) return;
const ratio = moneyMap[toCurrency] / moneyMap[fromCurrency];
return Number(amount) * ratio;
}, [amount, fromCurrency, toCurrency]);
return (
<>
<input type="number" value={amount} onChange={(e) => setAmount(e.target.value)} />
<select value={fromCurrency} onChange={(e) => setFromCurrency(e.target.value)}>
{Object.keys(moneyMap).map(currency => (
<option key={currency} value={currency}>{currency}</option>
))}
</select>
<select value={toCurrency} onChange={(e) => setToCurrency(e.target.value)}>
{Object.keys(moneyMap).map(currency => (
<option key={currency} value={currency}>{currency}</option>
))}
</select>
<div>{converted.toFixed(2)} {converted && toCurrency}</div>
</>
)
}
/* file: styles.css */
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36
Challenge Information:
Build a Currency Converter - Build a Currency Converter