Can i do server side rendering for my page without using redux or any store container and just react router. My initial page fetches some data from the api. How should i pass this down to the the react component on the server. If i use the window variable on the server i get an error saying window is undefined. Any help would be good.
I do not want to use, redux. I tried getting the initial data state, how do i pass this to the components on the server side. Using window variable doesnt help as window is not defined on the server.
clientRouter.get('/', (req, res) => {
match({routes : routes, location: req.url}, (err, redirect, props) => {
if (err) {
res.status(500).send(err.message)
} else if (redirect) {
res.redirect(redirect.pathname + redirect.search)
} else if (props) {
let todos = [{id: 1, title: "Hey loo"}, {id: 2, title: "Meoww"}];
props.todos = todos
**** how do i pass the todos state down to the components****
const appHtml = renderToString(<RouterContext {...props}/>);
res.send(renderPage(appHtml, todos))
// if we got props then we matched a route and can render
} else {
// no errors, no redirect, we just didn't match anything
res.status(404).send('Not Found')
}
})
})
The above did not work
function renderPage(appHtml, state) {
let initialState = JSON.stringify(state);
return `
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Judo Heroes - A Universal JavaScript demo application with React</title>
<link rel="stylesheet" href="./../build/${cssSrc}">
</head>
<body>
<div id="main">${appHtml}</div>
<script>window.INIT_STATE = ${initialState}</script>
<script src=./../build/${jsSrc}></script>
</body>
</html>
`
}
I have created a boilerplate in which the SSR is enabled using EJS.
I have used EJS(Embedded JS) for injecting the markup in html with preloaded data.
You can hit the api in server.js and load the data as preloadedData in your html markup