Skip to content

Commit 241188a

Browse files
sebmarkbagezhengjitf
authored andcommitted
Add more warnings for second argument to root.render. (facebook#23358)
We already had one for callbacks but containers is also an easy mistake.
1 parent 3996c47 commit 241188a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

packages/react-dom/src/__tests__/ReactDOMRoot-test.js

+31
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,37 @@ describe('ReactDOMRoot', () => {
5151
expect(callback).not.toHaveBeenCalled();
5252
});
5353

54+
it('warn if a container is passed to root.render(...)', async () => {
55+
function App() {
56+
return 'Child';
57+
}
58+
59+
const root = ReactDOM.createRoot(container);
60+
expect(() => root.render(<App />, {})).toErrorDev(
61+
'You passed a second argument to root.render(...) but it only accepts ' +
62+
'one argument.',
63+
{
64+
withoutStack: true,
65+
},
66+
);
67+
});
68+
69+
it('warn if a container is passed to root.render(...)', async () => {
70+
function App() {
71+
return 'Child';
72+
}
73+
74+
const root = ReactDOM.createRoot(container);
75+
expect(() => root.render(<App />, container)).toErrorDev(
76+
'You passed a container to the second argument of root.render(...). ' +
77+
"You don't need to pass it again since you already passed it to create " +
78+
'the root.',
79+
{
80+
withoutStack: true,
81+
},
82+
);
83+
});
84+
5485
it('warns if a callback parameter is provided to unmount', () => {
5586
const callback = jest.fn();
5687
const root = ReactDOM.createRoot(container);

packages/react-dom/src/client/ReactDOMRoot.js

+11
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,18 @@ ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = functio
104104
'render(...): does not support the second callback argument. ' +
105105
'To execute a side effect after rendering, declare it in a component body with useEffect().',
106106
);
107+
} else if (isValidContainer(arguments[1])) {
108+
console.error(
109+
'You passed a container to the second argument of root.render(...). ' +
110+
"You don't need to pass it again since you already passed it to create the root.",
111+
);
112+
} else if (typeof arguments[1] !== 'undefined') {
113+
console.error(
114+
'You passed a second argument to root.render(...) but it only accepts ' +
115+
'one argument.',
116+
);
107117
}
118+
108119
const container = root.containerInfo;
109120

110121
if (container.nodeType !== COMMENT_NODE) {

0 commit comments

Comments
 (0)