Phase 6: Favorite Fruit

Understand the Problem

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.

Devise a Plan

  1. Access the favorite fruit ID using useContext
  2. Find the corresponding fruit from the list of fruits
  3. Render a link to that fruit's show page
  4. If no fruit is selected, render nothing

Carry Out the Plan

File: 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;

Expected Input and Output

Explanation for New Developers

This 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.

Real World Analogy

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.

Bonus Tip

Want to style the favorite fruit differently? Add a CSS class like .highlight to make it stand out!