React Props

In React, props (short for properties) are a mechanism for passing data from a parent component to a child component. Props are read-only and allow components to be dynamic by providing them with inputs that can change. They are passed to child components as attributes in JSX and can be accessed in the child component using the props object.


Syntax of Props

Props are passed as attributes in JSX and can be accessed in the child component as follows:

</>
Copy
// Parent Component
function Parent() {
  return <Child name="Alice" age={25} />;
}

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

Passing Props: In the parent component, props are passed to the child component as attributes in JSX. For example, name="Alice" and age={25} are props passed to Child.

Accessing Props: In the child component, the props are accessed using the props object. For instance, props.name retrieves the value of the name prop, and props.age retrieves the value of the age prop.

Dynamic Rendering: The child component dynamically uses the values of props to display data, making the component reusable with different inputs.

This approach demonstrates how props enable parent-to-child communication in React components.


1 Passing Basic Props

In this example, we demonstrate how to pass and use basic props. The parent component sends a name and age to the child component.

App.js

</>
Copy
import React from 'react';

function Child(props) {
  return (
    <div>
      <p>Hello, {props.name}! You are {props.age} years old.</p>
    </div>
  );
}

function Parent() {
  return <Child name="Arjun" age={25} />;
}

export default Parent;

Explanation:

  • The parent component passes name and age as props to the child component.
  • The child component accesses these props using props.name and props.age.
  • Props make the child component reusable with different data.

Output: