DEV Community

Cover image for How to Pass Data Between Components in React
Thilina Dinelka
Thilina Dinelka

Posted on

How to Pass Data Between Components in React

in React, passing data between components is a common task. You often need to share data from a Parent component to child component using props (short for "properties").

What are Props?

you can think of props as arguments that you send to a function, but in this case sending them to a component.

Example: Passing data from Parent to Child

  1. Create Parent Component
import React from 'react';
import ChildComponent from './ChildComponent';

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

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

export default ParentComponent;
Enter fullscreen mode Exit fullscreen mode

2.Create Child Component

import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <h2>This is the Child Component</h2>
      <p>{props.message}</p>
    </div>
  );
}

export default ChildComponent;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)