Lecture Notes of Day 5: Components and Props in React

Rashmi Mishra
0

 

Lecture Notes of Day 5: Components and Props in React

Objective:

  • Understand React components and how data is passed between them using props.

Outcome:

  • Be able to create functional components.
  • Learn how to pass data via props to child components.

Introduction to React Components

In React, the core building block of an application is the component. Components are reusable pieces of code that define how a user interface (UI) should appear. They allow you to split the UI into independent, reusable parts, and think about each part in isolation.

There are two types of components in React:

1.  Functional Components: These are simpler components written as JavaScript functions. They are mostly used when no complex state or lifecycle methods are needed. With React hooks (like useState and useEffect), functional components can now handle state and side effects as well.

2.  Class Components: These are more complex components that were used before React introduced hooks. Class components can have their own state and lifecycle methods.

For beginners, we’ll focus on functional components as they are easier to understand and are commonly used in modern React development.


What Are Props?

Props (short for properties) are how data is passed between components in React. Props are like function arguments; they allow you to pass information from a parent component to a child component.

Think of props as a way to send data to a component from its parent. This data can be anything: strings, numbers, functions, arrays, or even other components.

Props are read-only. Once a component receives props, it cannot change them. The parent component controls the data, and the child component only receives it.


Creating Functional Components

Functional components are simply JavaScript functions that return JSX (JavaScript XML). JSX is the syntax extension that allows you to write HTML-like code within JavaScript.

Example of a Functional Component:

javascript

Copy code

import React from 'react';

 

// Define a functional component called 'Greeting'

function Greeting(props) {

  return <h1>Hello, {props.name}!</h1>;

}

 

// Export the component so it can be used in other parts of the app

export default Greeting;

In this example:

  • Greeting is a functional component.
  • It takes props as an argument, which contains data passed from a parent component.
  • Inside the component, we use props.name to access the name prop and display a personalized greeting.

Using Props to Pass Data Between Components

Once we have a functional component, we can use it inside another component by passing data via props.

Example of Parent and Child Components:

Let’s create a parent component that passes data to a child component using props.

javascript

Copy code

import React from 'react';

import Greeting from './Greeting'; // Import the Greeting component

 

// Define a Parent component

function ParentComponent() {

  const userName = 'John'; // This is the data we want to pass to the child

 

  return (

    <div>

      <h2>Welcome to React!</h2>

      {/* Passing the 'userName' data to the Greeting component as a prop */}

      <Greeting name={userName} />

    </div>

  );

}

 

export default ParentComponent;

In this example:

  • The ParentComponent defines a variable userName with the value 'John'.
  • The Parent passes userName to the Greeting component as a prop by writing <Greeting name={userName} />.
  • The Greeting component receives this prop as props.name and displays it.

This shows how data flows from the parent component to the child component using props.


Props Can Be Used to Pass Different Types of Data

Props can hold a variety of data types, including:

  • Strings and numbers
  • Arrays and objects
  • Functions

Example of Passing Different Data Types:

javascript

Copy code

import React from 'react';

 

// Child component receives multiple types of props

function UserCard(props) {

  return (

    <div>

      <h2>User Info</h2>

      <p>Name: {props.name}</p>

      <p>Age: {props.age}</p>

      <ul>

        {props.hobbies.map((hobby, index) => (

          <li key={index}>{hobby}</li>

        ))}

      </ul>

    </div>

  );

}

 

// Parent component

function App() {

  const user = {

    name: 'Alice',

    age: 25,

    hobbies: ['Reading', 'Traveling', 'Cooking'],

  };

 

  return (

    <div>

      <h1>Welcome to the User Profile</h1>

      {/* Passing an object and an array as props */}

      <UserCard name={user.name} age={user.age} hobbies={user.hobbies} />

    </div>

  );

}

 

export default App;

In this example:

  • The Parent component App creates a user object with name, age, and hobbies.
  • It then passes each part of the object (name, age, hobbies) as separate props to the UserCard component.
  • Inside UserCard, we can access these props and render them appropriately.

Passing Functions as Props

You can also pass functions as props to child components. This allows the child component to trigger actions or change the state in the parent component.

Example of Passing Functions as Props:

javascript

Copy code

import React, { useState } from 'react';

 

// Child component receives a function as a prop

function Button(props) {

  return <button onClick={props.handleClick}>Click Me</button>;

}

 

// Parent component

function App() {

  const [count, setCount] = useState(0);

 

  const handleButtonClick = () => {

    setCount(count + 1); // Increment count when the button is clicked

  };

 

  return (

    <div>

      <h1>Counter: {count}</h1>

      {/* Passing the handleButtonClick function as a prop */}

      <Button handleClick={handleButtonClick} />

    </div>

  );

}

 

export default App;

In this example:

  • The Button component receives the handleClick function as a prop.
  • When the button is clicked, the function is invoked, and it updates the count state in the parent component (App).

Summary

  • React Components are the building blocks of a React application, and functional components are commonly used for simpler implementations.
  • Props allow you to pass data from a parent component to a child component. They are read-only and are used to make components reusable.
  • You can pass strings, numbers, arrays, objects, and even functions as props.
  • To create reusable, modular UI components, you need to understand how to pass data efficiently using props.

Practice Exercise

1.  Create a functional component ProductCard that accepts name, price, and description as props and displays them in a card layout.

2.  Create a parent component ProductList that renders a list of ProductCard components, passing data to each one via props.



Post a Comment

0Comments

Post a Comment (0)