@samitouri / QOS-React-2 / commits / 68cb55f262

Add more warnings for second argument to root.render. (#23358)

We already had one for callbacks but containers is also an easy mistake.

Sebastian Markbåge committed Feb 24, 2022 at 16:31 UTC 68cb55f262b75f5d5b723104b830daab37b1ea14
2 files changed +42
packages/react-dom/src/__tests__/ReactDOMRoot-test.js
+31
@@ -51,6 +51,37 @@ describe('ReactDOMRoot', () => {
51 expect(callback).not.toHaveBeenCalled();
52 });
53
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 +
85 it('warns if a callback parameter is provided to unmount', () => {
86 const callback = jest.fn();
87 const root = ReactDOM.createRoot(container);
packages/react-dom/src/client/ReactDOMRoot.js
+11
@@ -104,7 +104,18 @@ ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = functio
104 'render(...): does not support the second callback argument. ' +
105 'To execute a side effect after rendering, declare it in a component body with useEffect().',
106 );
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 + );
117 }
118 +
119 const container = root.containerInfo;
120
121 if (container.nodeType !== COMMENT_NODE) {