Search code examples
reactjsstyled-components

How can I add styles to all the children of an element


For example how could I implement the addStyles function in this snippet

const addStyles = // ...
const Element = ({ children }) => (
    <div>{children.map(addStyles)}</div>
);

thanks


Solution

  • Use the React.Children.map function provided from facebook.

    Invokes a function on every immediate child contained within children with this set to thisArg. If children is a keyed fragment or array it will be traversed: the function will never be passed the container objects. If children is null or undefined, returns null or undefined rather than an array.

    Then return a clone of each child with an appropriate style like so using React.cloneElement. This will shallowly merge any property provided in the object in the second argument. Those you could use it to override current styles of the children. You could potentially provide { className: "newClassName" } as a second argument if you prefer.

    const StylishComponent = ({ children }) => {
        const iLikeBlueStyles = { color: "blue" };
    
        const clones = React.Children.map(children, child => {
            return React.cloneElement(child, { style: iLikeBlueStyles });
        });
    
        return (
            <div>
                {clones}
            </div>
        );
    };