I am working on a JS project for an online course where I am creating a budgeting app
I have the following components as part of my app
- Budget
- Remaining
- Spent so far
- Allocated Budget
- Change Allocation
I was tasked with creating a 6th component for the app “CurrencyDropdown” to house the different currency options to choose from. I have done this.
// CurrencyDropdown.js
import React, { useState } from 'react';
const CurrencyDropdown = () => {
const [selectedCurrency, setSelectedCurrency] = useState('$'); // Default currency
const handleCurrencyChange = (event) => {
setSelectedCurrency(event.target.value);
};
return (
<div className='alert alert-primary'>
<label htmlFor="currency">Currency:</label>
<select id="currency" value={selectedCurrency} onChange={handleCurrencyChange}>
<option value="$">$ Dollar</option>
<option value="£">£ Pound</option>
<option value="€">€ Euro</option>
<option value="₹">₹ Rupee</option>
{/* Add more currency options as needed */}
</select>
</div>
);
};
export default CurrencyDropdown;
The next task is to add code to the project so that when you change the currency from the CurrencyDropdown
, the currency displayed on all the other components across the app change to match the selected currency. That is where I got stuck.
I tried to create a new JS component CurrencyContext
:
// CurrencyContext.js
import React, { createContext, useContext, useState } from 'react';
const CurrencyContext = createContext();
export const CurrencyProvider = ({ children }) => {
const [selectedCurrency, setSelectedCurrency] = useState('USD');
const changeCurrency = (currency) => {
setSelectedCurrency(currency);
};
return (
<CurrencyContext.Provider value={{ selectedCurrency, changeCurrency }}>
{children}
</CurrencyContext.Provider>
);
};
export const useCurrency = () => {
return useContext(CurrencyContext);
};
I do not know how or where to apply this component to effect the change to the rest of my app.