We want to give users the ability to choose their favorite fruit from a dropdown. Once selected, the choice should update the app-wide context. We’ll need a controlled select input tied to the context value, and a function to update it when changed.
File: src/SetFavoriteFruit.jsx
// Pseudocode:
// 1. Access favFruitId and setFavFruitId from context
// 2. Render dropdown with fruit options
// 3. When changed, call setFavFruitId with the new ID
import { useContext } from 'react';
import { FavFruitContext } from '../context/FavFruitContext';
function SetFavoriteFruit({ fruits }) {
const { favFruitId, setFavFruitId } = useContext(FavFruitContext);
return (
<div className="set-fav-fruit">
<h2>Select your Favorite Fruit</h2>
<label>
<select value={favFruitId} onChange={e => setFavFruitId(e.target.value)}>
{fruits.map(fruit => (
<option key={fruit.id} value={fruit.id}>
{fruit.name}
</option>
))}
</select>
</label>
</div>
);
}
export default SetFavoriteFruit;
favFruitId updated to Banana’s IDThis is an example of using a controlled component with shared state. The dropdown’s value is tied to the app’s context. When the user picks something new, we use setFavFruitId to update it across the entire app.
This ensures the rest of the app knows which fruit is currently the user's favorite, including the FavoriteFruit component.
This is like setting your favorite music genre in a profile settings menu. Once selected, the app updates everywhere to reflect your preference. This dropdown works the same way — it's the user's settings control panel.
You can use localStorage to persist this value across page refreshes or sessions for a more advanced experience.