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

fix: simplify element before stringifying to avoid crash on docs page #19188

Merged
merged 2 commits into from
Jan 13, 2023
Merged
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
26 changes: 23 additions & 3 deletions code/renderers/react/src/docs/jsxDecorator.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-underscore-dangle */
import type { ReactElement } from 'react';
import React, { createElement } from 'react';
import type { ReactElement, ReactNode } from 'react';
import React, { isValidElement, createElement } from 'react';
import type { Options } from 'react-element-to-jsx-string';
import reactElementToJSXString from 'react-element-to-jsx-string';

Expand All @@ -13,6 +13,26 @@ import type { ReactRenderer } from '../types';

import { isMemo, isForwardRef } from './lib';

// Recursively remove "_owner" property from elements to avoid crash on docs page when passing components as an array prop (#17482)
// Note: It may be better to use this function only in development environment.
function simplifyNodeForStringify(node: ReactNode): ReactNode {
if (isValidElement(node)) {
const props = Object.keys(node.props).reduce<{ [key: string]: any }>((acc, cur) => {
acc[cur] = simplifyNodeForStringify(node.props[cur]);
return acc;
}, {});
return {
...node,
props,
_owner: null,
};
}
if (Array.isArray(node)) {
return node.map(simplifyNodeForStringify);
}
return node;
}

type JSXOptions = Options & {
/** How many wrappers to skip when rendering the jsx */
skip?: number;
Expand Down Expand Up @@ -108,7 +128,7 @@ export const renderJsx = (code: React.ReactElement, options: JSXOptions) => {
? reactElementToJSXString
: // @ts-expect-error (Converted from ts-ignore)
reactElementToJSXString.default;
let string: string = toJSXString(child, opts as Options);
let string: string = toJSXString(simplifyNodeForStringify(child), opts as Options);

if (string.indexOf('&quot;') > -1) {
const matches = string.match(/\S+=\\"([^"]*)\\"/g);
Expand Down