Deep dive into understanding Props in React

hassanshahzadaheer

Hassan Shahzad Aheer

Posted on September 2, 2023

Deep dive into understanding Props in React

1. What are Props?

  • Props (short for properties) are a fundamental concept in React.
  • Think of them as attributes you pass to a component, similar to HTML attributes in tags.
  • Props allow you to send data from a parent component to a child component.
  • They are read-only and help make your components dynamic and reusable.

2. Creating Props:

  • To create props, you include attributes in your component like this:

     <Contact name="Ali" />
    

3. Accessing Props:

  • In your child component, you access props using the props object:

     export default function Contact(props) {
       return (
         <h1>{props.name}</h1>
       );
     }
    

4. Destructuring Props:

  • Destructuring allows you to extract props more concisely.
  • Example:

     export default function Contact({ name }) {
       return (
         <h1>{name}</h1>
       );
     }
    
  • This is especially useful when you have multiple props.

5. Why Use Destructuring?

  • Destructuring props makes your code cleaner and more readable.
  • It reduces repetition by directly extracting the properties you need.
  • It also simplifies access to nested props.

6. Example:

  • Let's create a simple component that receives and displays user information using props and destructuring:
   // ParentComponent.js
   import React from 'react';
   import UserProfile from './UserProfile';

   export default function ParentComponent() {
     const user = {
       name: 'Ali',
       age: 30,
       city: 'New York',
     };

     return (
       <UserProfile user={user} />
     );
   }

   // UserProfile.js
   import React from 'react';

   export default function UserProfile({ user }) {
     return (
       <div>
         <h1>{user.name}</h1>
         <p>Age: {user.age}</p>
         <p>City: {user.city}</p>
       </div>
     );
   }
Enter fullscreen mode Exit fullscreen mode

7. Conclusion:

  • In React, props are like attributes you pass from parent to child components.
  • Destructuring props simplifies access and enhances code readability.
  • Understanding props is essential for building dynamic and reusable React applications.
💖 💪 🙅 🚩
hassanshahzadaheer
Hassan Shahzad Aheer

Posted on September 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

AM NEW INTO CODING
webdev AM NEW INTO CODING

October 11, 2024

Deploying a (static) Vite React app
webdev Deploying a (static) Vite React app

November 14, 2024

Request - Custom Hooks
webdev Request - Custom Hooks

November 9, 2024