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!
CodePudding user response:
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.
https://reactjs.org/docs/context.html
CodePudding user response:
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;
CodePudding user response:
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/App.js
More info: How to pass props to {this.props.children}