React Props Explained with Examples

React Props Explained with Examples

·

4 min read

Prerequisites : Whenever you start a project, you always need to do PROPER PLANNING first.
Never start your project before planning.
Proper planning starts with making a Wireframe/Mock of your entire UI.
That'll make you understand which all components must be required.

Eg : We're making a Food Ordering APP. Let's Start with Wireframing it first and then list down the required components

Header -> Logo & Nav Items
Body -> Search & (Restaurant Container -> Restaurant Card)
Footer -> Copyright, Links, Address & Contact

This made it very much easier now to start executing our project.

*Now Let's Dive Deep & study more about React Functional Components and Props

  • PROPS (short form for properties) : To pass data to Components (React Functional Components RFC)
    And what is RFC at the end of the day - Just Normal JS Functions right!
    So Props are just normal arguments we pass to these functions

Passing a PROP to a RFC is just like Passing an argument to a JS Function

const RestaurantCard = (props) =>{
 console.log(props); 
//! React will Wrap all the passed props into an object
{
    "imgSrc": "image1.png",
    "resName": "Meghana Foods",
    "cuisine": "Pizzas, Burgers, Beverages",
    "rating": "4.5",
    "deliveryTime": "60-90 mins",
    "locality": "Kormangala, Bangalore"
}

 return (
   <div className="res-card" style={styleCard}>
     <img
       className="res-logo"
       src={props.imgSrc}
       alt="res-img"
     />
     <h3>{props.resName}</h3>//! As Props is a JS object and to use JS in JSX we do it in {..}
     <div className="res-info">
       <span>{props.rating} • </span>
       {props.deliveryTime}
     </div>
     <h4>{props.cuisine}</h4>
      <h4>{props.locality}</h4>
   </div>
 );
}

const Body = () =>{
 return (
   <div>
    <div className="search">Search</div>
    <div className="res-container">
     <RestaurantCard resName="KFC" cuisine="Burgers, Fast Food" 
     rating="4.1" deliveryTime="50-60 mins" locality="Linking Road, Bandra"
     imgSrc="/image1.png"/>

     <RestaurantCard resName="Bhagwati Pav Bhaji" cuisine="South Indian, Pav Bhaji, Pulav" 
     rating="3.2" deliveryTime="25-30 mins" locality="Iraniwadi, Kandivali"
     imgSrc="/image2.png"/>
    </div>
   </div>
 )
}

Can also De-structure the props - This Is JS and not React which can do all this (As props is a JS obj)
Do Learn about Destructuring in JS

const RestaurantCard = (props) =>{
 // console.log(props); //! Wrap all the passed props into an object

 // DESTRUCTURING
 const {resData} = props;
 const {cloudinaryImageId,name, avgRatingString, cuisines, deliveryTime, locality} = resData?.info; //* Use Optional Chaining - to avoid errors

 return (
    <div className="res-card" style={styleCard}>
      <img
        className="res-logo"
        src={"https://media-assets.swiggy.com/image/"+cloudinaryImageId}
        alt="res-img"
      />
      <h3>{name}</h3>
      <div className="res-info">
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" role="img" aria-hidden="true" strokecolor="rgba(2, 6, 12, 0.92)" fillcolor="rgba(2, 6, 12, 0.92)"><circle cx="10" cy="10" r="9" fill="url(#StoreRating20_svg__paint0_linear_32982_71567)"></circle><path d="M10.0816 12.865C10.0312 12.8353 9.96876 12.8353 9.91839 12.865L7.31647 14.3968C6.93482 14.6214 6.47106 14.2757 6.57745 13.8458L7.27568 11.0245C7.29055 10.9644 7.26965 10.9012 7.22195 10.8618L4.95521 8.99028C4.60833 8.70388 4.78653 8.14085 5.23502 8.10619L8.23448 7.87442C8.29403 7.86982 8.34612 7.83261 8.36979 7.77777L9.54092 5.06385C9.71462 4.66132 10.2854 4.66132 10.4591 5.06385L11.6302 7.77777C11.6539 7.83261 11.706 7.86982 11.7655 7.87442L14.765 8.10619C15.2135 8.14085 15.3917 8.70388 15.0448 8.99028L12.7781 10.8618C12.7303 10.9012 12.7095 10.9644 12.7243 11.0245L13.4225 13.8458C13.5289 14.2757 13.0652 14.6214 12.6835 14.3968L10.0816 12.865Z" fill="white"></path><defs><linearGradient id="StoreRating20_svg__paint0_linear_32982_71567" x1="10" y1="1" x2="10" y2="19" gradientUnits="userSpaceOnUse"><stop stopColor="#21973B"></stop><stop offset="1" stopColor="#128540"></stop></linearGradient></defs></svg>
        <span>{avgRatingString} • </span>
        {deliveryTime}
      </div>
      <h4>{cuisines}</h4>
       <h4>{locality}</h4>
    </div>
  );
 }

 const AllRestaurants =()=>{
  return (
    <div className="res-near">
       <h1>Restaurants near you</h1>
       <div className="res-container">
         {resList.map((restaurants) => (
           // For each restaurants => return a (JSX) i.e <RestaurantCard /> (and pass data to it)
           <RestaurantCard key={restaurants.info.id} resData={restaurants} />
         ))}
       </div>
     </div>
  )
 }

Apply CSS in React
1. Inlining Styling in JSX

  • In JSX style takes in. JS OBJ and we write whatever is JS in {..}

  • And style attributes should be camelCased

2. In css file using className & id

3. Tailwind CSS (we'll study soon about it 😍), Material UI, etc

To avoid this Warning - This occurs when do not pass a key prop to a component

1. We need to pass a unique key to each child
2. Each of the Array items should be uniquely represented

Whenever we're looping onto any Array. A unique key/id should be passed to each

{
      resList.map(restaurants => 
       // For each restaurants => return a (JSX) i.e <RestaurantCard /> (and pass data to it)
      <RestaurantCard resData={restaurants} key={restaurants.info.id}/>)
     }

// OR PASS INDEX (Do not use this)

{
      resList.map((restaurants, index) => 
       // For each restaurants => return a (JSX) i.e <RestaurantCard /> (and pass data to it)
      <RestaurantCard key={index} resData={restaurants}/>)
     }

So Whenever you do a map always pass unique key to (use an index number or a more fancy ID from your data)

BUT REACT itself says that It's not recommended to pass INDEXES (In documentation)

not passing key (unacceptable) <<< using index as keys (when in data there is no unique id) <<< using unique id from data (best)

But Why do we need keys for each?
https://www.linkedin.com/feed/update/urn:li:activity:7091636639826944000/
Very Important:
It takes a big performance hit if you don't pass key prop.
It will Re render everything (every card) which can be a very costly task.
If you pass key then it'll not re render everything just the newly added card will be rendered
Eg: On scroll if you want to just append new cards to the page