Props Drilling . . .

_Khojiakbar_ - Aug 9 - - Dev Community

1. Setting Up the Pirates (Components)

We'll create a Captain, FirstMate, SecondMate, ThirdMate, and FourthMate component. The Captain will pass the "treasure map" (prop) down through each level to finally reach the FourthMate.

2. Props Drilling in Action

import React from 'react';

// Fourth Mate (Deep Child Component)
const FourthMate = ({ map }) => {
  return (
    <div>
      <h2>Fourth Mate</h2>
      <p>Arrr! I got the treasure map: {map}</p>
    </div>
  );
};

// Third Mate (Child Component)
const ThirdMate = ({ map }) => {
  return (
    <div>
      <h2>Third Mate</h2>
      <FourthMate map={map} />
    </div>
  );
};

// Second Mate (Child Component)
const SecondMate = ({ map }) => {
  return (
    <div>
      <h2>Second Mate</h2>
      <ThirdMate map={map} />
    </div>
  );
};

// First Mate (Child Component)
const FirstMate = ({ map }) => {
  return (
    <div>
      <h2>First Mate</h2>
      <SecondMate map={map} />
    </div>
  );
};

// Captain (Parent Component)
const Captain = () => {
  const treasureMap = "X marks the spot!";

  return (
    <div>
      <h1>Captain</h1>
      <p>"Ahoy! Take this map and find the treasure!"</p>
      <FirstMate map={treasureMap} />
    </div>
  );
};

// App Component
const App = () => {
  return (
    <div>
      <Captain />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Explanation

  • Captain Component: The parent component holds the treasureMap data and starts the props drilling by passing it to the FirstMate.

  • FirstMate Component: Receives the map prop from Captain and passes it to SecondMate.

  • SecondMate Component: Receives the map prop from FirstMate and passes it to ThirdMate.

  • ThirdMate Component: Receives the map prop from SecondMate and passes it to FourthMate.

  • FourthMate Component: Finally receives the map prop and displays it.

This code mimics the pirate crew passing the treasure map down through the ship's decks until it reaches the one who needs it most!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player