'React Router Dom v6 - Functions are not valid as a React child
Im trying to upgrade to v6 of react router dom. The application works but I cant seem to get the testcases to work.
Before we had this wrapper for jest:
const render = (ui: React.FC, path: string, route: string): RenderResult => {
const history = createMemoryHistory({ initialEntries: [route] });
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
return {
...render(
<QueryClientProvider client={queryClient}>
<Router history={history}>
<Route path={path} component={ui} />
</Router>
</QueryClientProvider>,
),
};
};
After following the documentation for v6 I got the application to work and I updated the wrapper for jest to the following solution:
return {
...render(
<QueryClientProvider client={queryClient}>
<Router location={history.location} navigator={history}>
<Routes>
<Route path={path} element={ui} />
</Routes>
</Router>
</QueryClientProvider>,
),
};
This results in the following error:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
Majority of the components in the project are function components. So getting this to work is kinda vital. :/
Solution 1:[1]
The syntax for rendering a component into a Route
in RRDv6 is as a JSX literal instead of as a reference to the component.
Example:
<Route path="/thepath" element={<MyComponent />} />
For your example it's the ui
component that must be rendered as JSX. Rename ui
to Ui
so it's a valid React component and render accordingly.
const render = (Ui: React.FC, path: string, route: string): RenderResult => {
const history = createMemoryHistory({ initialEntries: [route] });
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
return {
...render(
<QueryClientProvider client={queryClient}>
<Router location={history.location} navigator={history}>
<Route
path={path}
element={<Ui />} // <-- JSX, not reference
/>
</Router>
</QueryClientProvider>,
),
};
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Drew Reese |