Passing Data Between Components in React

Smart ShockSmart Shock
2 min read

One of the most important features of React is the ability to pass data between components. In this article, we'll explore how to pass data between a parent component and a child component in React.

The Parent Component

First, let's create our parent component. In this example, we'll call it ParentComponent. It will render a child component and pass data to it via props.

import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const data = 'Hello from Parent Component';

  return (
    <div>
      <ChildComponent data={data} />
    </div>
  );
}

export default ParentComponent;

The ParentComponent renders a ChildComponent and passes a data prop to it. The value of the data prop in this example is the string "Hello from Parent Component".

The Child Component

Next, let's create our child component. In this example, we'll call it ChildComponent. It will receive data from its parent via props and display it in the browser.

import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <p>{props.data}</p>
    </div>
  );
}

export default ChildComponent;

The ChildComponent receives a data prop from its parent and renders it in a p element.

The App Component

Finally, let's create our App component. This component will render the ParentComponent.

import React from 'react';
import ParentComponent from './ParentComponent';

function App() {
  return (
    <div>
      <ParentComponent />
    </div>
  );
}

export default App;

The App component renders the ParentComponent and displays it in the browser.

Conclusion

In this article, we explored how to pass data between a parent component and a child component in React. We created a parent component that rendered a child component and passed data to it via props. We also created a child component that received data from its parent and displayed it in the browser. Finally, we created an App component that rendered the ParentComponent.

By understanding how to pass data between components in React, we can create more flexible and reusable code.

10
Subscribe to my newsletter

Read articles from Smart Shock directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Smart Shock
Smart Shock