'Parameterizing rendering of parent component from child
I have a Parent component that contains a Child component. Suppose that the Parent wants to ask the Child its preferred background color and uses it to modify how the Parent renders itself:
class Child extends React.Component {
favoriteColor = () => "red";
render = () => (<span>Hello world</span>);
}
class Parent extends React.Component {
render = () => {
const child = (<Child />);
return (
<div style={{backgroundColor: child.favoriteColor()}}>
{child}
</div>
);
};
}
What is the idiomatic way to do this in React?
In my real project, I have a Parent component that has a dynamic set of children. The Parent wraps each child in a React Bootstrap <Col>. But sometimes a child does not want to be rendered, and the correct thing would be to omit the <Col>. So the Parent component needs to be able to ask each child "do you have anything to render?"
Solution 1:[1]
One way to do this depending on the circumstances is to declare Child.favoriteColor as static. As a static function it has no access to the instance's props or state.
class Child extends React.Component {
static favoriteColor = () => "red";
render = () => (<span>Hello world</span>);
}
class Parent extends React.Component {
render = () => {
return (
<div style={{backgroundColor: Child.favoriteColor()}}>
<Child />
</div>
);
};
}
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 |
