Skip to content

Bug: cloneElement does not correctly merge styles when used in nested components #32531

@User6531

Description

@User6531

Description:

I encountered an issue when using React.cloneElement in two separate components that wrap an SVG icon. When both components use cloneElement, the styles from the first wrapper are lost in the second wrapper.

Steps to Reproduce:

  1. IconResizer applies width, height, and flexShrink styles.
  2. IconColorizer applies color: #FFC700.
  3. When both are used together, only the styles from IconResizer remain, and the color is not applied.

Code Example:

import React, { cloneElement, ReactElement } from 'react';

const IconResizer = ({ children }: { children: ReactElement }) => {
  return cloneElement(children, {
    style: { height: '16px', width: '16px', flexShrink: 0 },
  });
};

const IconColorizer = ({ children }: { children: ReactElement }) => {
  return cloneElement(children, {
    style: { ...(children.props.style || {}), color: '#FFC700' },
  });
};

const MyIcon = () => (
  <IconResizer>
    <IconColorizer>
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M14.0001 24C13.7837 24..."
          fill="currentColor"
        />
      </svg>
    </IconColorizer>
  </IconResizer>
);

export default MyIcon;

Expected Behavior:

The svg element should have both height: 16px, width: 16px, flexShrink: 0 and color: #FFC700 applied.

Actual Behavior:

  • The height and width from IconResizer are applied correctly.
  • The color from IconColorizer is missing.

Environment:

  • React version: 18.3.1
  • Browser: chrome

Possible Cause:

It seems that the second cloneElement is not properly merging the styles from the first cloneElement. This behavior is unexpected, as cloneElement is supposed to preserve existing props while overriding the specified ones.


Additional Notes:

  • If I manually spread the styles when creating the first cloneElement, the issue persists.
  • Using a single cloneElement works fine, but nesting them causes the first one's styles to be lost.

Would appreciate insights on whether this is expected behavior or a bug. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution: StaleAutomatically closed due to inactivityStatus: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions