0

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!

ccprp
  • 1
  • 1
    You can use [states](https://reactjs.org/docs/hooks-state.html) or even global states ([context](https://reactjs.org/docs/context.html) or [redux](https://redux-toolkit.js.org/) ) to pass down the values to child components – Kaung Khant Zaw Apr 03 '22 at 08:23

3 Answers3

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

vahid tajari
  • 1,163
  • 10
  • 20
nong tran
  • 11
  • 2
0

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;
Chun
  • 407
  • 4
  • 10
0

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}

coglialoro
  • 601
  • 1
  • 4
  • 12