Sossenbinder
Sossenbinder

Reputation: 5302

How do I append values to the props of a react components children?

I am wondering whether the following I want to do it possible. Essentially, I am planning on creating a bunch of tsx components which allow me to create CSS Grids in component form. Here is what I imagined:

<Grid limit={12}>
    <Cell width={6} />
    <Cell width={6} />
</Grid>

In this case, the grid should limit the width to 12, and the Cells should work on that value. So in this example:

grid-column: 6 / 12;

So, for convenience purposes, it would be awesome if I could do something like this within the Grid.tsx component:

export const Grid: React.FC<GridProps> = ({ 
    className,
    style,
    children,
}) => {

    const classes = classNames({
        "grid": true,
    });

    children?.forEach(x => x.props["limit"] = 12);

    return (
        <div 
            className={`${classes} ${className}`}
            style={style}>
            { children }
        </div>
    )
}

so that I don't have to specify the limit for every child Cell explicitly.

However, I have yet to figure out how. Is there a way to do this, extending the props of a child components from the respective parent?

Upvotes: 1

Views: 279

Answers (1)

James
James

Reputation: 1098

You can use cloneElement. This will preserve existing props on the child elements.

import React, { cloneElement } from 'react';

export const Grid = ({ children, limit }) => (
   <div>
      {
         children.map(child => (
            cloneElement(child, { limit })
         )
      }
   </div>
);

Upvotes: 1

Related Questions