Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[utils] skip deep clone React element (v5.x) #44494

Open
wants to merge 1 commit into
base: v5.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/mui-utils/src/deepmerge/deepmerge.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as React from 'react';
import { expect } from 'chai';
import { runInNewContext } from 'vm';
import deepmerge from './deepmerge';
Expand Down Expand Up @@ -122,4 +123,12 @@ describe('deepmerge', () => {
expect(result).to.deep.equal({ foo: { baz: 'new test' } });
expect(foo).to.deep.equal({ foo: { baz: 'test' } });
});

it('should not deep clone React element', () => {
const element = React.createElement('div', {}, React.createElement('span'));
const element2 = React.createElement('a');
const result = deepmerge({ element }, { element: element2 });

expect(result.element).to.equal(element2);
});
});
8 changes: 6 additions & 2 deletions packages/mui-utils/src/deepmerge/deepmerge.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as React from 'react';

// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
export function isPlainObject(item: unknown): item is Record<keyof any, unknown> {
if (typeof item !== 'object' || item === null) {
Expand All @@ -19,7 +21,7 @@ export interface DeepmergeOptions {
}

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

Expand All @@ -41,7 +43,9 @@ export default function deepmerge<T>(

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