I am facing an issue while setting up SSR for a react app.The Server side code for the render is as below:
app.use((req, res) => {
const context = {}
const body = ReactDOMServer.renderToString(
React.createElement(
Provider, { store },
React.createElement(
StaticRouter, { location: req.url, context: context },
React.createElement(Layout, null, React.createElement(Routes))
)
)
)
if (context.url) {
res.redirect(context.url)
} else {
res.status(200).send(template({ body }))
}
})
The route config is as below: Routes.js
const Routes = () => {
return (
<Switch>
<Route path="/" exact component={Home}/>
<Route path="*" component={NotFound}/>
</Switch>
)
}
export default Routes
App.js
const App = () => {
return (
<Provider store={store}>
<BrowserRouter>
<Layout>
{router}
</Layout>
</BrowserRouter>
</Provider>
);
}
export default App
It throwing the below error:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
TypeError: element.type.toLowerCase is not a function
at ReactDOMServerRenderer.renderDOM (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2304:28)
at ReactDOMServerRenderer.render (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2298:21)
at ReactDOMServerRenderer.read (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2234:19)
at Object.renderToString (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2501:25)
at app.use (../server.js:59:33)
When i tried printing console.log(React.createElement(Routes));
it shows as below:
{ '$$typeof': Symbol(react.element),
type: [Function: Routes],
key: null,
ref: null,
props: {},
_owner: null,
_store: {} }
I have created the CompiledRoutes file from the Routes file using babel and I am importing it into server.js as below:
const Routes = require('./client/CRoutes').default
Can someone pls guide me what could be the issue here?Thanks in advance.
Try changing
React.createElement(Layout, null, React.createElement(Routes))
to
React.createElement(Layout, null, React.createElement(Routes.default))
You might be using require
on the server-side, instead of import
, which results in some discrepancies.