I set up a react router with server side rendering and a 2 routes, one route should redirect me to some page, currently "/popular/php", but that doesn't work, it doesn't redirect me anywhere, If I remove the redirect component and just render something on "/" path then that works.
I have this routes files.
import Home from './Home.js';
import Grid from './Grid.js';
import { fetchPopularRepos } from './api';
const routes = [
{
path: '/popular/:id',
component: Grid,
fetchInitialData: (path = '') => fetchPopularRepos (
path.split('/').pop()
)
}
]
export default routes
This is the App component where routing is done. If I am not mistaken then if I hit "/" url, the redirect component should sent me to "/popular/php" page, but nothing is happening when I hit "/" url.
import React from 'react';
import Grid from './Grid.js';
import routes from './routes';
import { Route, Switch, Redirect } from 'react-router-dom'
import Navbar from './Navbar';
import Login from './Login';
class App extends React.Component {
render() {
return (
<div>
<Navbar />
<Switch>
<Route exact path="/" render={() => (
<Redirect to="/popular/php"/>)} />
{routes.map(({ path, exact, component: C, ...rest }) => (
<Route
key={path}
path={path}
exact={exact}
render={(props) => (
<C {...props} {...rest} />
)}
/>
))}
</Switch>
</div>
)
}
}
export default App
Server.js
import express from 'express';
import cors from 'cors';
import { renderToString } from 'react-dom/server';
import App from '../shared/App.js';
import React from 'react';
import serialize from 'serialize-javascript';
import { matchPath, StaticRouter } from 'react-router-dom';
import routes from '../shared/routes.js';
const app = express();
app.use(cors());
app.use(express.static('public'));
app.get('*', (req, res, next) => {
const activeRoute = routes.find(
(route) => matchPath(req.url, route)) || {};
const promise = activeRoute.fetchInitialData ?
activeRoute.fetchInitialData(req.path)
: Promise.resolve();
promise.then((data) => {
const context = { data };
const markup = renderToString(
<StaticRouter location={req.url} context={ context }>
<App />
</StaticRouter>);
res.send(`<!DOCTYPE html>
<html>
<head>
<title>SSR with RR</title>
<script src="/bundle.js"></script>
<script>window.__INITIAL_DATA__ = ${serialize(data)}</script>
</head>
<body>
<div id="app">${markup}</div>
</body>
</html>`)
}).catch(next);
})
app.listen(3000, () => {
console.log("Server is running on port 3000");
})