'Pass prop from parent to child in React

I have the following page:

import ParentComponent from '../components/ParentComponent';
import ChildComponent from '../components/ChildComponent';

const Page = () => {
  return (
    <ParentComponent color="white">
      <ChildComponent />
    </ParentComponent>
  );

}

export default Page;

Is there a way to access the color prop on the ParentComponent from inside the ChildComponent so I can manipulate some things based on if it's set to 'white'?

I haven't tried anything yet, please help!



Solution 1:[1]

You can use Context in React. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

More information

Solution 2:[2]

How about using a state to store the color and pass it to both components?

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

const Page = () => {
  const [color, setColor] = useState('white')
  return (
    <ParentComponent color={color}>
      <ChildComponent color={color} />
    </ParentComponent>
  );

}

export default Page;

Solution 3:[3]

In your parent component you can clone your children and add a property to them like this:

  {React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { color });
    }
  })}

Demo: https://stackblitz.com/edit/react-6p9qfb?file=src%2FApp.js

More info: How to pass props to {this.props.children}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vahid tajari
Solution 2 Chun
Solution 3 coglialoro