Flat Preloader Icon

Using Props

Using props in React allows you to pass data from one component to another, typically from a parent component to a child component. Here’s a step-by-step guide on how to use props in React:

Step 1: Define the Parent Component

The parent component holds the data that you want to pass to the child component. You define the data within the parent component and then pass it to the child component as props.
				
					// ParentComponent.jsx
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const message = "Hello from the Parent!";
  const count = 42;

  return (
    <div>
      <h1>Parent Component</h1>
      <ChildComponent message={message} count={count} />
    </div>
  );
}

export default ParentComponent;

				
			

Step 2: Define the Child Component

The child component receives the props and uses them within its rendering logic. Props are accessed via the props object in class components or directly in the function parameter list in functional components.
				
					// ChildComponent.jsx
import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <h2>Child Component</h2>
      <p>{props.message}</p>
      <p>Count: {props.count}</p>
    </div>
  );
}

export default ChildComponent;

				
			

Step 3: Pass Props from Parent to Child

In the parent component, you pass the data as attributes on the child component element. Each attribute name will become a prop in the child component.
				
					// ParentComponent.jsx
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const message = "Hello from the Parent!";
  const count = 42;

  return (
    <div>
      <h1>Parent Component</h1>
      <ChildComponent message={message} count={count} />
    </div>
  );
}

export default ParentComponent;

				
			

Step 4: Access Props in the Child Component

In the child component, you access the props and use them as needed.
				
					// ChildComponent.jsx
import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <h2>Child Component</h2>
      <p>{props.message}</p>
      <p>Count: {props.count}</p>
    </div>
  );
}

export default ChildComponent;

				
			
In this example, the ParentComponent defines a state variable count and a function incrementCount. The function is passed as a prop to the ChildComponent, which calls it when the button is clicked, thus allowing the child component to update the parent’s state.