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.
2
Answers
To use the
CurrencyProvider
anduseCurrency
the rest of the app, you need to wrap your entire application or the relevant part of it with theCurrencyProvider
. This will make theselectedCurrency
andchangeCurrency
available to all components nested within it.Like this wrap the entire app with the
currencyProvider
and this will effect the change throughout the app.To use your
CurrencyContext.js
, wrap your application with<CurrencyProvider/>
Example
This will allow other components to use your currency context. Note that all components that uses the
CurrencyContext
should be children ofCurrencyProvider
You may now use
selectedCurrency
andchangeCurrency
inCurrencyDropdown.js
And in other components such as
Remaining.js
, you can now useselectedCurrency