How to Pass Props Between React Components?

17 minutes read

To pass props between React components, you can follow the below steps:

  1. In the parent component, define the prop you want to pass down to its child component(s). Props can be any JavaScript value, including strings, numbers, objects, or functions.
  2. When rendering the child component(s), include the prop as an attribute within the JSX syntax. For example, if the prop is called "name", you can pass it down by writing .
  3. In the child component, access the passed prop by referencing this.props.propName within the component's code. You can use the prop value within the child component to render dynamic content or perform actions.
  4. If needed, the child component can also pass the received prop(s) further down to its own child components by repeating the process described above.


By passing props from parent components to child components in this manner, you can enable data and behavior sharing among React components, creating a more modular and reusable code structure.

Best React.js Books to Read in 2024

1
The Road to React: Your journey to master plain yet pragmatic React.js

Rating is 5 out of 5

The Road to React: Your journey to master plain yet pragmatic React.js

2
React Key Concepts: Consolidate your knowledge of React's core features

Rating is 4.9 out of 5

React Key Concepts: Consolidate your knowledge of React's core features

3
React and React Native: A complete hands-on guide to modern web and mobile development with React.js, 3rd Edition

Rating is 4.8 out of 5

React and React Native: A complete hands-on guide to modern web and mobile development with React.js, 3rd Edition

4
React Cookbook: Create dynamic web apps with React using Redux, Webpack, Node.js, and GraphQL

Rating is 4.7 out of 5

React Cookbook: Create dynamic web apps with React using Redux, Webpack, Node.js, and GraphQL

5
React 18 Design Patterns and Best Practices: Design, build, and deploy production-ready web applications with React by leveraging industry-best practices

Rating is 4.6 out of 5

React 18 Design Patterns and Best Practices: Design, build, and deploy production-ready web applications with React by leveraging industry-best practices

6
Learn React with TypeScript: A beginner's guide to reactive web development with React 18 and TypeScript

Rating is 4.5 out of 5

Learn React with TypeScript: A beginner's guide to reactive web development with React 18 and TypeScript

7
React and React Native: Build cross-platform JavaScript applications with native power for the web, desktop, and mobile, 4th Edition

Rating is 4.4 out of 5

React and React Native: Build cross-platform JavaScript applications with native power for the web, desktop, and mobile, 4th Edition

8
React Application Architecture for Production: Learn best practices and expert tips to deliver enterprise-ready React web apps

Rating is 4.3 out of 5

React Application Architecture for Production: Learn best practices and expert tips to deliver enterprise-ready React web apps

9
React: The Comprehensive Guide

Rating is 4.2 out of 5

React: The Comprehensive Guide


How to pass props between sibling components?

To pass props between sibling components in React, you can follow these steps:

  1. Create a parent component that contains both sibling components.
  2. Define a state in the parent component that holds the data you want to pass.
  3. Pass a callback function from the parent component to the first sibling component as a prop.
  4. In the first sibling component, call the callback function whenever you need to update the data.
  5. Update the state in the parent component using the callback function, and pass the updated data as a prop to the second sibling component.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// ParentComponent.js
import React, { useState } from 'react';
import SiblingComponent1 from './SiblingComponent1';
import SiblingComponent2 from './SiblingComponent2';

const ParentComponent = () => {
  const [data, setData] = useState('');

  const updateData = newData => {
    setData(newData);
  };

  return (
    <div>
      <SiblingComponent1 updateData={updateData} />
      <SiblingComponent2 data={data} />
    </div>
  );
};

export default ParentComponent;


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// SiblingComponent1.js
import React from 'react';

const SiblingComponent1 = ({ updateData }) => {
  const handleClick = () => {
    const newData = 'Hello from Sibling 1';
    updateData(newData);
  };

  return (
    <button onClick={handleClick}>Update Data</button>
  );
};

export default SiblingComponent1;


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// SiblingComponent2.js
import React from 'react';

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

export default SiblingComponent2;


In this example, when the button in SiblingComponent1 is clicked, it calls updateData function defined in the parent component ParentComponent to update the data state. The updated data is then passed as a prop to SiblingComponent2, allowing it to display the updated value.


How to pass props from child to parent components?

In React, data is typically passed from parent components to child components through props. If you want to pass data from a child component back to its parent component, you can achieve this through function callbacks.


Here's how you can pass props from a child component to its parent component:

  1. In the parent component, define a callback function that will receive the data from the child component. This function will be passed as a prop to the child component.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [childData, setChildData] = useState('');

  const handleChildData = (data) => {
    setChildData(data);
  };

  return (
    <div>
      <ChildComponent onChildData={handleChildData} />
      <p>Data from child: {childData}</p>
    </div>
  );
};

export default ParentComponent;


  1. In the child component, define an event handler that will send the data back to the parent component. This event handler is typically triggered by an interaction within the child component, such as a button click or a form submission.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// ChildComponent.js

import React, { useState } from 'react';

const ChildComponent = ({ onChildData }) => {
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    onChildData(inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default ChildComponent;


  1. Now, when the child component calls the onChildData callback function, it will send the entered data back to the parent component. The parent component will then update its state and re-render itself, displaying the received data.


In this example, when the user enters some data in the text input and submits the form, the handleSubmit function in the child component is called. It calls the onChildData function received from the parent component, passing the entered data as an argument. The parent component receives the data, updates its childData state, and displays the received data in the p element.


This way, you can pass data from the child component to the parent component using props and callback functions.


How to pass props to a higher-order component (HOC)?

To pass props to a higher-order component (HOC), you can follow these steps:

  1. Define a higher-order component function that takes a component as its argument and returns a new component wrapped with the desired functionality. const withProps = (WrappedComponent) => { return class extends React.Component { render() { // Add or modify props here const modifiedProps = { ...this.props, // Add new prop or modify existing prop newProp: 'value', }; // Render the wrapped component with modified props return ; } }; };
  2. Use the higher-order component by passing the target component as an argument to the higher-order component function. const MyComponent = (props) => { // Access modified props passed from the higher-order component console.log(props.newProp); //... }; // Apply the higher-order component to MyComponent const WrappedComponent = withProps(MyComponent); // Render the wrapped component ReactDOM.render(, document.getElementById('root'));


In the above example, the withProps higher-order component function accepts a component WrappedComponent and returns a new component. It modifies the props received by adding a new prop newProp with the value value. Finally, it renders WrappedComponent with the modified props.


You can access the modified props in the MyComponent by using the props.newProp syntax.

Best React.js Hosting Providers in 2024

1
DigitalOcean

Rating is 5 out of 5

DigitalOcean

2
AWS

Rating is 4.9 out of 5

AWS

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways


How to pass props in Next.js?

In Next.js, you can pass props to components using the getServerSideProps or getStaticProps functions.

  1. getServerSideProps: This function runs on every request and fetches data from an API or a database. It is used when you need to get fresh data for every request.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
export async function getServerSideProps() {
  // Fetch data from an API
  const res = await fetch('https://example.com/api/data');
  const data = await res.json();

  // Pass the data as props to the component
  return {
    props: {
      data
    }
  };
}

// Inside your component
export default function MyComponent({ data }) {
  // Use the passed props
  // ...
}


  1. getStaticProps: This function runs at build time and fetches data from an API or a database. It is used when the data is static and doesn't change frequently.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
export async function getStaticProps() {
  // Fetch data from an API
  const res = await fetch('https://example.com/api/data');
  const data = await res.json();

  // Pass the data as props to the component
  return {
    props: {
      data
    }
  };
}

// Inside your component
export default function MyComponent({ data }) {
  // Use the passed props
  // ...
}


You can access the passed props in your components by destructuring them in the component's parameters.


How to pass functions as props in React?

To pass functions as props in React, follow these steps:

  1. In the parent component, define the function that you want to pass as a prop.
1
2
3
4
5
6
7
function ParentComponent() {
  const handleClick = () => {
    // logic to handle the click event
  };

  return <ChildComponent handleClick={handleClick} />;
}


  1. In the child component, specify the prop and use it as needed.
1
2
3
4
5
6
7
function ChildComponent(props) {
  return (
    <button onClick={props.handleClick}>
      Click me
    </button>
  );
}


In this example, the handleClick function is defined in the ParentComponent and passed as a prop called handleClick to the ChildComponent. In the ChildComponent, it is accessed using props.handleClick and assigned to the onClick event of the button.


When the button is clicked, the handleClick function from the parent component will be triggered.


What is destructuring props in React?

Destructuring props in React is a way to extract specific values from the props object and assign them to individual variables. This allows for easier and cleaner access to the desired values without referencing the props object every time.


In React, components receive data and functionality through properties, commonly referred to as props. When destructuring props, instead of accessing the values directly from the props object like props.name or props.age, we can directly assign them to separate variables using the ES6 destructuring syntax.


For example, consider the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const Person = (props) => {
  const { name, age } = props;
  
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}


In this example, the name and age properties are extracted from the props object and assigned to individual variables using destructuring. These variables can then be directly used within the component without having to reference props each time.


Using destructuring props can make the code more concise and readable, especially when dealing with multiple props or deeply nested objects.


What are props in React?

In React, props (short for properties) are a way to pass data from a parent component to its child components. Props are read-only and are used to configure the child components and pass the necessary data for rendering.


Props are similar to function parameters or arguments in regular programming. They allow components to be reusable and independent of each other. By changing the values of props in the parent component, you can control the behavior and appearance of the child components.


Props can be of any data type and can include primitive values, objects, arrays, functions, or even other React components. They are passed to child components as attributes in the JSX syntax and can be accessed using the props object within the child component.


Here's an example of passing props to a child component in React:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Parent component
function App() {
  const user = {
    name: "John Doe",
    age: 25,
  };

  return (
    <div>
      <h1>Welcome to my app!</h1>
      <UserInfo user={user} />
    </div>
  );
}

// Child component
function UserInfo(props) {
  return (
    <div>
      <h2>User Information:</h2>
      <p>Name: {props.user.name}</p>
      <p>Age: {props.user.age}</p>
    </div>
  );
}


In this example, the user object is passed as a prop to the UserInfo component. It is then accessed within the component using props.user.name and props.user.age.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

In Vue.js, there are multiple ways to share data between components. Some options include using props, a centralized state management system such as Vuex, event bus, or the provide/inject API.Props: You can pass data from a parent component to a child componen...
In React, routing between pages can be efficiently handled using a library called React Router. React Router is a third-party package that allows us to define the navigation paths and render different components based on the URL. Here&#39;s how you can route b...
To redirect after logging in to a React.js application, you can make use of the react-router-dom library. The steps to accomplish this are as follows:Install react-router-dom package by running npm install react-router-dom or yarn add react-router-dom in your ...