Reputation: 334
I'm implementing a nested component and all of my components need to have variable prop, now I have:
<Parent variable="myVariable">
<Child1 variable="myVariable" />
<Child2 variable="myVariable" />
</Parent>
But I don't want to pass the prop directly to each component and I need something like this:
<Parent variable="myVariable">
<Child1 />
<Child2 />
</Parent>
and I need to get access to variable prop from Child1 and Child2.
Upvotes: 6
Views: 3701
Reputation: 4176
There is two solutions to do this. Using React.createContext or React.cloneElement in your Parent component.
I highly recommend using React.createContext in React 16.3+ since this is exactly what React Context is meant for. Its also especially helpful if you have flow to keep
prop
type checking working properly.Note in React 16.6 its even easier to use context by using contextType.
https://reactjs.org/docs/context.html
(or using create-react-context https://github.com/jamiebuilds/create-react-context) if you're not up to date.
// parentFile.js
import * as React from 'react';
export const MyContext = React.createContext(); // React.createContext accepts a defaultValue as the first param
type Props = {
variable: string,
children: React.Node
};
class Parent extends React.Component<Props> {
render() {
return (
<MyContext.Provider value={{ variable: this.props.variable }}>
{this.props.children}
</MyContext.Provider>
);
}
}
class Child1 extends Component<{}> {
static contextType = MyContext;
render() {
return (<div>{this.context.variable}</div>);
}
}
// IF you have a child in a different file make sure you import the correct consumer
// child2.js
import * as React from 'react';
import { MyContext } from './parentFile';
class Child2 extends Component<{}> {
static contextType = MyContext;
render() {
return (<span>{this.context.variable}</span>);
}
}
React.createContext shines here where you can handle nested components
// Example of using Parent and Child
import * as React from 'react';
class SomeComponent extends React.Component<{}> {
render() {
<Parent variable="test">
<Child1 />
{ /* Previously you couldn't use
React.cloneElement to handle the nested case */ }
<SomeOtherComp>
<Child2 />
</SomeOtherComp>
</Parent>
}
}
This is a quick example of how to do this without React Context and using React.cloneElement
import * as React from 'react';
class Parent extends Component {
render() {
const { children, props } = this.props;
return (
React.Children.map(children, child =>
React.cloneElement(child, {...props})
)
);
}
}
Upvotes: 10
Reputation: 138537
You could pass the children as props to parent:
class Wrapper extends React.Component {
render() {
return (
this.props.wraps.map(El => <El {...this.props} />);
};
}
}
So you can do:
<Wrapper wraps = {[Child1, Child2]} variable = "whatever" />
Upvotes: 2