Sunday, 10 November 2024

Building Reusable Components using component properties

Component properties, commonly referred to as "props," are a fundamental concept in React that allows you to pass data and event handlers between components.

What are Component Properties (Props)?

Props are short for "properties." They are a way of passing data from a parent component to a child component in React.

 

Props are read-only in the child component, meaning the child cannot modify them. This immutability helps maintain predictable data flow.

 

Benefits of Using Props

1.   Data Flow: Props facilitate a unidirectional data flow, making it easier to understand and manage data changes throughout your application.

2.   Reusability: By passing different props to the same component, you can create reusable components that render differently based on the data provided.

3.   Separation of Concerns: Props help in separating data (state) from the UI, allowing for cleaner component design.

 

How to Pass Props to a Component

You can pass props to a component by adding attributes to the component tag in JSX.

 

Example

function ParentComponent() {
    const user = {
        name: "Ram",
        age: 36
    };

    return (
        <ChildComponent name={user.name} age={user.age} />
    );
}

 

You can even pass all the properties of an object using Object Spread Syntax.

const employee = {
  name: "Rama Krishan",
  position: "Software Engineer",
  email: "krishna@example.com",
  address: {
    street: "Chowdeswari Street",
    city: "Bangalore",
  },
  hobbies: ["Reading", "Cycling", "Cooking"],
  experiences: [
    "Company A: 2018 - Present (Software Engineer)",
    "Company B: 2015 - 2018 (Junior Developer)"
  ],
};

<EmployeeProfile {...employee}/>

 

The ... syntax (spread operator) takes the properties inside the employee object and spreads them as individual props. This way, the EmployeeProfile component will receive all the properties of employee object as individual props.

 

How to Read Props in a Component?

Props can be accessed in the child component using the props object.

function ChildComponent(props) {
    return (
        <div>
            <h1>Name: {props.name}</h1>
            <p>Age: {props.age}</p>
        </div>
    );
}

 

Alternatively, you can use destructuring for cleaner syntax.

function ChildComponent({ name, age }) {
    return (
        <div>
            <h1>Name: {name}</h1>
            <p>Age: {age}</p>
        </div>
    );
}

 

Find the below working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘component-properties’.

 

Project structure looks like below. 


 

Step 2: Create a folder components in src/ folder and define EmployeeProfile.jsx file.

 

EmployeeProfile.jsx

function EmployeeBasicDetails({ name, position, email }) {
    return (
      <div>
        <h2>Employee Name: {name}</h2>
        <h3>Position: {position}</h3>
        <h3>Email: {email}</h3>
      </div>
    );
  }
  
  function Address(props) {
    return (
      <div>
        <h3>Address:</h3>
        <p>{props.street}, {props.city}</p>
      </div>
    );
  }
  
  function Hobbies({ hobbies }) {
    return (
      <div>
        <h3>Hobbies:</h3>
        <ul>
          {hobbies.map((hobby, index) => <li key={index}>{hobby}</li>)}
        </ul>
      </div>
    );
  }
  
  function Experience({ experiences }) {
    return (
      <div>
        <h3>Experience:</h3>
        <ul>
          {experiences.map((exp, index) => (
            <li key={index}>{exp}</li>
          ))}
        </ul>
      </div>
    );
  }
  
  export default function EmployeeProfile(employee) {
    return (
      <div>
        <EmployeeBasicDetails 
          name={employee.name} 
          position={employee.position} 
          email={employee.email} 
        />
        <Address 
          street={employee.address.street} 
          city={employee.address.city} 
        />
        <Hobbies hobbies={employee.hobbies} />
        <Experience experiences={employee.experiences} />
      </div>
    );
  }

Step 3: Update main.jsx file like below.

 

main.jsx 

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import EmployeeProfile from './components/EmployeeProfile.jsx';

const employee = {
  name: "Rama Krishan",
  position: "Software Engineer",
  email: "krishna@example.com",
  address: {
    street: "Chowdeswari Street",
    city: "Bangalore",
  },
  hobbies: ["Reading", "Cycling", "Cooking"],
  experiences: [
    "Company A: 2018 - Present (Software Engineer)",
    "Company B: 2015 - 2018 (Junior Developer)"
  ],
};

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <EmployeeProfile {...employee}/>
  </StrictMode>,
)

 

Step 4: Build and run the application by executing below commands.

cd component-properties
npm install
npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see below kind of screen.


 

You can download this application from this link.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment