Menu

Passing Props to Child Component

Passing Props to Child Component

Passing props means sending data from a parent component to a child component. In React, props are used to share information like values or functions, so the child component can use them. This helps in keeping components reusable and makes data flow clear and structured.

<div
                  key={recipe.id}
                  className="dish flex flex-col cursor-pointer"
                  onClick={() => {
                    setSelectedRecipe(recipe);
}}
                >
                  <div className="img-container">
                    <img src={recipe.thumbnail_url} alt={recipe.name} />
                  </div>
                  <div className="dish-text p-3">
                    <p className="name text-lg line-clamp-1">{recipe.name}</p>
                    <p className="text-base mt-2 sm:mt-3">
                      <span className="prep -ml-0.75">⏱ Prep Time:</span>{" "}
                      {recipe.total_time_minutes
? recipe.total_time_minutes < 60
? `${recipe.total_time_minutes} mins`
: `${(recipe.total_time_minutes / 60).toFixed(1)} hrs`
: "N/A"}
                    </p>
                  </div>
                </div>

-----------------

      <RecipeModal
        recipe={selectedRecipe}
        onClose={() => setSelectedRecipe(null)}
      />

-----------------

// Modal Dialog Component
function RecipeModal({ recipe, onClose }) {
  if (!recipe) return null;
  return (
    <>
{/* Code displays ingredients and cooking instructions in a modal dialog */}
    </>
);
}

Explanation:

  • RecipeModal is a child component that receives data from the parent via props. When you click a recipe card, setSelectedRecipe(recipe) is called, which stores the clicked recipe in the state.

  • This selectedRecipe is then passed to RecipeModal as a prop (recipe={selectedRecipe}), along with onClose. As a result, the child component now has access to the selected recipe data.

  • Inside RecipeModal, it first checks if (!recipe), which returns null, meaning the modal will not show until a recipe is selected. Once a recipe is available, the modal opens and displays all the details like image, ingredients, and cooking instructions using the passed data. The ingredients and steps are dynamically shown using map() from the recipe object.

  • To close the modal, both the close icon and the close button use onClick={onClose}, which calls setSelectedRecipe(null) in the parent. This removes the recipe data, so the condition becomes false again, and the modal disappears. This is how props control opening and closing, and how data flows smoothly from parent to child.