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 renderToString fails with array type children when react-dom/server render #10221

Merged
merged 27 commits into from
Jul 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
790e65a
fix(*): fix renderToString fails with array type children when react-…
evilbs Jul 19, 2017
c2aeb06
Merge remote-tracking branch 'upstream/master'
evilbs Jul 20, 2017
6fd78e5
Add an integration test that verify renderToString with array type ch…
evilbs Jul 20, 2017
4b28bc1
Add integration test to renderToString with array type child
Jul 20, 2017
f652ed7
Add integration test to renderToString with array type child
Jul 20, 2017
322fa40
Merge remote-tracking branch 'origin/master'
Jul 20, 2017
deb11af
Update integration test to renderToString with array type child
Jul 20, 2017
62c042e
fix renderToString fails with array type children when react-dom/serv…
Jul 20, 2017
6b4eb0e
Update integration test to renderToString with array type child
Jul 21, 2017
e53e552
Add to iterate that are not arrays
Jul 21, 2017
eafb4bd
Add the validation react element
Jul 21, 2017
3df964d
Improve an integration test of server renderToString with array type
Jul 22, 2017
6f7f142
Merge branch 'master' of https://github.com/facebook/react
Jul 22, 2017
02101d5
prettier
Jul 22, 2017
d661c5a
Merge branch 'master' of https://github.com/facebook/react
Jul 25, 2017
97575fd
Merge branch 'master' into master
evilbs Jul 27, 2017
e0bd356
Remove array validate
Jul 28, 2017
1d45bae
Merge branch 'master' of https://github.com/gzhappysky/react
Jul 28, 2017
5f8a2dd
prettier
Jul 28, 2017
cf005dd
Make SSR can handle a single array element and nested array
Jul 29, 2017
7f5c0a1
prettier
Jul 29, 2017
60e7e3e
Change integeration test description
Jul 29, 2017
e4dd558
modified: src/renderers/dom/ReactDOMNodeStreamRenderer.js
Jul 31, 2017
59e0843
Make invariants consistent
gaearon Jul 31, 2017
5539f09
Gate outdated test itself by feature flag
gaearon Jul 31, 2017
06d9971
Change test to make sense both with old and new code
gaearon Jul 31, 2017
b42dd08
Test more cases
gaearon Jul 31, 2017
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
54 changes: 54 additions & 0 deletions src/renderers/__tests__/ReactComponent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

var React;
var ReactDOM;
var ReactDOMServer;
var ReactDOMFeatureFlags;
var ReactTestUtils;

Expand All @@ -24,6 +25,7 @@ describe('ReactComponent', () => {
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
ReactTestUtils = require('react-dom/test-utils');
});
Expand Down Expand Up @@ -439,4 +441,56 @@ describe('ReactComponent', () => {
' in Foo (at **)',
);
});

it('throws if a plain object is used as a child when using SSR', async () => {
var children = {
x: <span />,
y: <span />,
z: <span />,
};
var element = <div>{[children]}</div>;
var ex;
try {
ReactDOMServer.renderToString(element);
} catch (e) {
ex = e;
}
expect(ex).toBeDefined();
expect(normalizeCodeLocInfo(ex.message)).toBe(
'Objects are not valid as a React child (found: object with keys ' +
'{x, y, z}). If you meant to render a collection of children, use ' +
'an array instead.' +
// Fiber gives a slightly better stack with the nearest host components
(ReactDOMFeatureFlags.useFiber ? '\n in div (at **)' : ''),
);
});

it('throws if a plain object even if it is in an owner when using SSR', async () => {
class Foo extends React.Component {
render() {
var children = {
a: <span />,
b: <span />,
c: <span />,
};
return <div>{[children]}</div>;
}
}
var container = document.createElement('div');
var ex;
try {
ReactDOMServer.renderToString(<Foo />, container);
} catch (e) {
ex = e;
}
expect(ex).toBeDefined();
expect(normalizeCodeLocInfo(ex.message)).toBe(
'Objects are not valid as a React child (found: object with keys ' +
'{a, b, c}). If you meant to render a collection of children, use ' +
'an array instead.\n' +
// Fiber gives a slightly better stack with the nearest host components
(ReactDOMFeatureFlags.useFiber ? ' in div (at **)\n' : '') +
' in Foo (at **)',
);
});
});
23 changes: 15 additions & 8 deletions src/renderers/dom/ReactDOMNodeStreamRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
var invariant = require('fbjs/lib/invariant');
var React = require('react');
var ReactPartialRenderer = require('ReactPartialRenderer');
var ReactFeatureFlags = require('ReactFeatureFlags');

var Readable = require('stream').Readable;

Expand All @@ -40,10 +41,13 @@ class ReactMarkupReadableStream extends Readable {
* See https://facebook.github.io/react/docs/react-dom-stream.html#rendertostream
*/
function renderToStream(element) {
invariant(
React.isValidElement(element),
'renderToStream(): You must pass a valid ReactElement.',
);
const disableNewFiberFeatures = ReactFeatureFlags.disableNewFiberFeatures;
if (disableNewFiberFeatures) {
invariant(
React.isValidElement(element),
'renderToStream(): You must pass a valid ReactElement.',
);
}
return new ReactMarkupReadableStream(element, false);
}

Expand All @@ -53,10 +57,13 @@ function renderToStream(element) {
* See https://facebook.github.io/react/docs/react-dom-stream.html#rendertostaticstream
*/
function renderToStaticStream(element) {
invariant(
React.isValidElement(element),
'renderToStaticStream(): You must pass a valid ReactElement.',
);
const disableNewFiberFeatures = ReactFeatureFlags.disableNewFiberFeatures;
if (disableNewFiberFeatures) {
invariant(
React.isValidElement(element),
'renderToStaticStream(): You must pass a valid ReactElement.',
);
}
return new ReactMarkupReadableStream(element, true);
}

Expand Down
23 changes: 15 additions & 8 deletions src/renderers/dom/ReactDOMStringRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,21 @@
var invariant = require('fbjs/lib/invariant');
var React = require('react');
var ReactPartialRenderer = require('ReactPartialRenderer');
var ReactFeatureFlags = require('ReactFeatureFlags');

/**
* Render a ReactElement to its initial HTML. This should only be used on the
* server.
* See https://facebook.github.io/react/docs/react-dom-server.html#rendertostring
*/
function renderToString(element) {
invariant(
React.isValidElement(element),
'renderToString(): You must pass a valid ReactElement.',
);
const disableNewFiberFeatures = ReactFeatureFlags.disableNewFiberFeatures;
if (disableNewFiberFeatures) {
invariant(
React.isValidElement(element),
'renderToString(): You must pass a valid ReactElement.',
);
}
var renderer = new ReactPartialRenderer(element, false);
var markup = renderer.read(Infinity);
return markup;
Expand All @@ -36,10 +40,13 @@ function renderToString(element) {
* See https://facebook.github.io/react/docs/react-dom-server.html#rendertostaticmarkup
*/
function renderToStaticMarkup(element) {
invariant(
React.isValidElement(element),
'renderToStaticMarkup(): You must pass a valid ReactElement.',
);
const disableNewFiberFeatures = ReactFeatureFlags.disableNewFiberFeatures;
if (disableNewFiberFeatures) {
invariant(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems too early. It only validates top-level element, but not its children. What I was referring to is that we have this validation in PartialRenderer and it should probably throw in some cases otherwise. Validation should happen as we resolve children rather than at the top.

Copy link
Contributor Author

@evilbs evilbs Jul 24, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😃 I understand what you mean. I fell that children do not need validation. Because when resolve method meet array type children , It will return to render method, The render method will check if child is a array type, If it is then push to stack. So resolve method only validates single element child and do not validates array type children.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but don't we still want to throw if it's neither array nor valid element?

Copy link
Contributor Author

@evilbs evilbs Jul 26, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can use 'React.children.toArray', It will accept valid element or valid array, otherwise it will throw an error.

  1. When children is single element: It will be validated by React.isValidElement.
  2. When children is array type: It will be validated whether the array is valid, It can either array(native array) or object that have iterator function. and per element of array will be validated by React.isValidElement.

So we can validated the following cases by React.children.toArray:

  1. First call to render, ReactDOMServer.renderToString(reactElement)
  2. Element be returned by render method.

React.isValidElement(element),
'renderToStaticMarkup(): You must pass a valid ReactElement.',
);
}
var renderer = new ReactPartialRenderer(element, true);
var markup = renderer.read(Infinity);
return markup;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,19 @@ describe('ReactDOMServerIntegration', () => {
});

describe('basic rendering', function() {
beforeEach(() => {
onAfterResetModules = () => {
const ReactFeatureFlags = require('ReactFeatureFlags');
ReactFeatureFlags.disableNewFiberFeatures = false;
};

resetModules();
});

afterEach(() => {
onAfterResetModules = null;
});

itRenders('a blank div', async render => {
const e = await render(<div />);
expect(e.tagName).toBe('DIV');
Expand All @@ -347,6 +360,70 @@ describe('ReactDOMServerIntegration', () => {
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.tagName).toBe('BR');
});

if (ReactDOMFeatureFlags.useFiber) {
itRenders('a array type children as a child', async render => {
let Header = props => {
return <p>header</p>;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's also make the component return array as well. This way we verify it's supported at multiple levels rather than just top level.

};
let Footer = props => {
return [<h2 key={1}>footer</h2>, <h3 key={2}>about</h3>];
};
let e = await render([
<div key={1}>text1</div>,
<span key={2}>text2</span>,
<Header key={3} />,
<Footer key={4} />,
]);
let parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('SPAN');
expect(parent.childNodes[2].tagName).toBe('P');
expect(parent.childNodes[3].tagName).toBe('H2');
expect(parent.childNodes[4].tagName).toBe('H3');
});

itRenders('a single array element children as a child', async render => {
let e = await render([<div key={1}>text1</div>]);
let parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
});

itRenders('a nested array children as a child', async render => {
let e = await render([
[<div key={1}>text1</div>],
<span key={1}>text2</span>,
[[[null, <p key={1} />], false]],
]);
let parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('SPAN');
expect(parent.childNodes[2].tagName).toBe('P');
});

itRenders('an iterable as a child', async render => {
const threeDivIterable = {
'@@iterator': function() {
var i = 0;
return {
next: function() {
if (i++ < 3) {
return {value: <div key={i} />, done: false};
} else {
return {value: undefined, done: true};
}
},
};
},
};
let e = await render(threeDivIterable);
let parent = e.parentNode;
expect(parent.childNodes.length).toBe(3);
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('DIV');
expect(parent.childNodes[2].tagName).toBe('DIV');
});
}
});

describe('property to attribute mapping', function() {
Expand Down
21 changes: 14 additions & 7 deletions src/renderers/dom/shared/__tests__/ReactServerRendering-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ var ReactMarkupChecksum;
var ReactReconcileTransaction;
var ReactTestUtils;
var PropTypes;
var ReactFeatureFlags;

var ID_ATTRIBUTE_NAME;
var ROOT_ATTRIBUTE_NAME;
Expand All @@ -35,6 +36,9 @@ describe('ReactDOMServer', () => {
ReactReconcileTransaction = require('ReactReconcileTransaction');
PropTypes = require('prop-types');

ReactFeatureFlags = require('ReactFeatureFlags');
ReactFeatureFlags.disableNewFiberFeatures = false;

ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
ExecutionEnvironment.canUseDOM = false;
ReactDOMServer = require('react-dom/server');
Expand Down Expand Up @@ -319,8 +323,12 @@ describe('ReactDOMServer', () => {

it('should throw with silly args', () => {
expect(
ReactDOMServer.renderToString.bind(ReactDOMServer, 'not a component'),
).toThrowError('renderToString(): You must pass a valid ReactElement.');
ReactDOMServer.renderToString.bind(ReactDOMServer, {x: 123}),
).toThrowError(
ReactDOMFeatureFlags.useFiber
? 'Objects are not valid as a React child (found: object with keys {x})'
: 'renderToString(): You must pass a valid ReactElement.',
);
});
});

Expand Down Expand Up @@ -431,12 +439,11 @@ describe('ReactDOMServer', () => {

it('should throw with silly args', () => {
expect(
ReactDOMServer.renderToStaticMarkup.bind(
ReactDOMServer,
'not a component',
),
ReactDOMServer.renderToStaticMarkup.bind(ReactDOMServer, {x: 123}),
).toThrowError(
'renderToStaticMarkup(): You must pass a valid ReactElement.',
ReactDOMFeatureFlags.useFiber
? 'Objects are not valid as a React child (found: object with keys {x})'
: 'renderToStaticMarkup(): You must pass a valid ReactElement.',
);
});

Expand Down
25 changes: 18 additions & 7 deletions src/renderers/shared/server/ReactPartialRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,6 @@ function createOpenTagMarkup(
}

function resolve(child, context) {
// TODO: We'll need to support Arrays (and strings) after Fiber is rolled out
invariant(
!Array.isArray(child),
'The server renderer does not implement support for array children yet.',
);
while (React.isValidElement(child)) {
if (__DEV__) {
pushElementToDebugStack(child);
Expand Down Expand Up @@ -418,8 +413,9 @@ function resolve(child, context) {

class ReactDOMServerRenderer {
constructor(element, makeStaticMarkup) {
var children = React.isValidElement(element) ? [element] : toArray(element);
var topFrame = {
children: [element],
children,
childIndex: 0,
context: emptyObject,
footer: '',
Expand Down Expand Up @@ -487,7 +483,22 @@ class ReactDOMServerRenderer {
if (child === null || child === false) {
return '';
} else {
return this.renderDOM(child, context);
if (React.isValidElement(child)) {
return this.renderDOM(child, context);
} else {
var children = toArray(child);
var frame = {
children,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
frame.debugElementStack = [];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to do this? (Note: I'm not very familiar with this code so I'm learning it too.)

Copy link
Contributor Author

@evilbs evilbs Jul 20, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"setCurrentDebugStack" method will set debugElementStack.length = 1, This is to init the debugElementStack array. The same method handles when HostCompoment return array type children.https://github.com/facebook/react/blob/master/src/renderers/shared/server/ReactPartialRenderer.js#L769

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do warnings still work? You can add a test similar to this one but using an array.

Copy link
Contributor Author

@evilbs evilbs Jul 20, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gaearo, It's done. Please review.

}
this.stack.push(frame);
return '';
}
}
}
}
Expand Down