Mark As Completed Discussion

Passing Data between Components

In React, passing data between components is a common requirement. There are various approaches you can take to achieve this, depending on the relationship between the components and the nature of the data being passed.

Parent-to-Child

One way to pass data from a parent component to a child component is through props. Props allow you to pass data and functions as properties from a parent component to a child component.

Here's an example:

JAVASCRIPT
1// Parent component
2import React, { useState } from 'react';
3import ChildComponent from './ChildComponent';
4
5const ParentComponent = () => {
6  const [message, setMessage] = useState('Hello from parent!');
7
8  const handleMessageChange = (newMessage) => {
9    setMessage(newMessage);
10  };
11
12  return (
13    <div>
14      <h1>Parent Component</h1>
15      <p>Message: {message}</p>
16      <ChildComponent
17        message={message}
18        onMessageChange={handleMessageChange}
19      />
20    </div>
21  );
22};
23
24export default ParentComponent;

In this example, the parent component (ParentComponent) has a message state that is initially set to 'Hello from parent!'. It passes this message state to the child component (ChildComponent) as a prop called message. It also passes a function called handleMessageChange as a prop called onMessageChange.

The child component can access and display the message prop, and when it needs to update the message, it can call the onMessageChange function provided by the parent component.

Child-to-Parent

To pass data from a child component to a parent component, you can define a callback function in the parent component and pass it to the child component as a prop. The child component can then call this callback function and pass the data as an argument.

Here's an example:

JAVASCRIPT
1// Child component
2import React from 'react';
3
4const ChildComponent = ({ message, onMessageChange }) => {
5  const handleChange = (event) => {
6    onMessageChange(event.target.value);
7  };
8
9  return (
10    <div>
11      <h2>Child Component</h2>
12      <p>Message from parent: {message}</p>
13      <input type="text" value={message} onChange={handleChange} />
14    </div>
15  );
16};
17
18export default ChildComponent;

In this example, the child component (ChildComponent) receives the message prop from the parent component and displays it. When the input field value changes, the handleChange function is called, which invokes the onMessageChange function provided by the parent component and passes the new message as an argument.

Passing data between components is an essential part of building React applications. It allows components to communicate and share information, enabling dynamic and interactive user interfaces.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment