We want to show the user's favorite fruit using React Context. The context gives us access to the ID of the currently selected favorite fruit, and we need to display a link to that fruit's detail page.
useContextFile: src/FavoriteFruit.jsx
// Pseudocode:
// 1. Import useContext and context
// 2. Get favFruitId from context
// 3. Find fruit in array
// 4. If found, return a link
import { useContext } from 'react';
import { FavFruitContext } from '../context/FavFruitContext';
import { Link } from 'react-router-dom';
function FavoriteFruit({ fruits }) {
const { favFruitId } = useContext(FavFruitContext);
const fruit = fruits.find(f => f.id === favFruitId);
if (!fruit) return null;
return (
<div className="fav-fruit">
<h2>Favorite Fruit</h2>
<Link to={`/fruits/${fruit.id}`}>{fruit.name}</Link>
</div>
);
}
export default FavoriteFruit;
favFruitId = '2', and fruits has id '2'/fruits/2 with name of the fruitThis is how we “share” state across unrelated components in a React app. useContext grabs shared values like the favorite fruit’s ID, and we use that to search and render the relevant fruit info.
We avoid errors by checking that the fruit exists before trying to render it.
Imagine asking a friend what their favorite fruit is. They say “banana.” You look it up in your fruit guide and show them a card about bananas. This component does the same: gets the choice, finds the match, and displays it.
Want to style the favorite fruit differently? Add a CSS class like .highlight to make it stand out!