Skip to content

Commit

Permalink
Add more warnings for second argument to root.render. (#23358)
Browse files Browse the repository at this point in the history
We already had one for callbacks but containers is also an easy mistake.
  • Loading branch information
sebmarkbage committed Feb 24, 2022
1 parent 8c4cd65 commit 68cb55f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
31 changes: 31 additions & 0 deletions packages/react-dom/src/__tests__/ReactDOMRoot-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,37 @@ describe('ReactDOMRoot', () => {
expect(callback).not.toHaveBeenCalled();
});

it('warn if a container is passed to root.render(...)', async () => {
function App() {
return 'Child';
}

const root = ReactDOM.createRoot(container);
expect(() => root.render(<App />, {})).toErrorDev(
'You passed a second argument to root.render(...) but it only accepts ' +
'one argument.',
{
withoutStack: true,
},
);
});

it('warn if a container is passed to root.render(...)', async () => {
function App() {
return 'Child';
}

const root = ReactDOM.createRoot(container);
expect(() => root.render(<App />, container)).toErrorDev(
'You passed a container to the second argument of root.render(...). ' +
"You don't need to pass it again since you already passed it to create " +
'the root.',
{
withoutStack: true,
},
);
});

it('warns if a callback parameter is provided to unmount', () => {
const callback = jest.fn();
const root = ReactDOM.createRoot(container);
Expand Down
11 changes: 11 additions & 0 deletions packages/react-dom/src/client/ReactDOMRoot.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,18 @@ ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = functio
'render(...): does not support the second callback argument. ' +
'To execute a side effect after rendering, declare it in a component body with useEffect().',
);
} else if (isValidContainer(arguments[1])) {
console.error(
'You passed a container to the second argument of root.render(...). ' +
"You don't need to pass it again since you already passed it to create the root.",
);
} else if (typeof arguments[1] !== 'undefined') {
console.error(
'You passed a second argument to root.render(...) but it only accepts ' +
'one argument.',
);
}

const container = root.containerInfo;

if (container.nodeType !== COMMENT_NODE) {
Expand Down

0 comments on commit 68cb55f

Please sign in to comment.