Skip to content

Commit

Permalink
[utils] Do not deep merge React component (#45058)
Browse files Browse the repository at this point in the history
  • Loading branch information
siriwatknp authored Jan 21, 2025
1 parent bea77fb commit 57639f9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
11 changes: 11 additions & 0 deletions packages/mui-utils/src/deepmerge/deepmerge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@ describe('deepmerge', () => {
expect(result.element).to.equal(element2);
});

it('should not deep clone React component', () => {
// most 3rd-party components use `forwardRef`
const Link = React.forwardRef((props, ref) => React.createElement('a', { ref, ...props }));
const result = deepmerge(
{ defaultProps: { component: 'a' } },
{ defaultProps: { component: Link } },
);

expect(result.defaultProps.component).to.equal(Link);
});

it('should deep clone example correctly', () => {
const result = deepmerge({ a: { b: 1 }, d: 2 }, { a: { c: 2 }, d: 4 });

Expand Down
5 changes: 3 additions & 2 deletions packages/mui-utils/src/deepmerge/deepmerge.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react';
import { isValidElementType } from 'react-is';

// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
export function isPlainObject(item: unknown): item is Record<keyof any, unknown> {
Expand All @@ -21,7 +22,7 @@ export interface DeepmergeOptions {
}

function deepClone<T>(source: T): T | Record<keyof any, unknown> {
if (React.isValidElement(source) || !isPlainObject(source)) {
if (React.isValidElement(source) || isValidElementType(source) || !isPlainObject(source)) {
return source;
}

Expand Down Expand Up @@ -61,7 +62,7 @@ export default function deepmerge<T>(

if (isPlainObject(target) && isPlainObject(source)) {
Object.keys(source).forEach((key) => {
if (React.isValidElement(source[key])) {
if (React.isValidElement(source[key]) || isValidElementType(source[key])) {
(output as Record<keyof any, unknown>)[key] = source[key];
} else if (
isPlainObject(source[key]) &&
Expand Down

0 comments on commit 57639f9

Please sign in to comment.