im using react and I have a component that simply needs to render the children and add them a class according to a condition. Whats the best way of doing it?
React Components and Children In React, a component can have one, many, or no children.
There is no way to pass props up to a parent component from a child component. We will revisit this caveat later in this tutorial. It's also important to note that React's props are read only (immutable). As a developer, you should never mutate props but only read them in your components.
I figured it out a week ago, this is what I wanted :
export default class ContainerComponent extends React.Component { constructor(props) { super(props); this.modifyChildren = this.modifyChildren.bind(this); } modifyChildren(child) { const className = classNames( child.props.className, {...otherClassses} ); const props = { className }; return React.cloneElement(child, props); } render() { return (<div> {React.Children.map(this.props.children, child => this.modifyChildren(child))} </div>); } }
For the sake of simplicity:
const StyleInjector = ({ children }) => { const StyledChildren = () => React.Children.map(children, child => React.cloneElement(child, { className: `${child.props.className} ${PUT_YOUR_CLASS_HERE}` }) ); return <StyledChildren />; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With