Example of StaticRouterProvider
Code Example: This example demonstrates how StaticRouterProvider is used on the server side to render React components dynamically based on the requested URL.
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const { StaticRouter,
BrowserRouter,
Route,
Switch } = require('react-router-dom');
const server = express();
server.use(express.static('build'));
const Home = () => <div>Home Page</div>;
const About = () => <div>About Page</div>;
server.get('*', (req, res) => {
const context = {};
const serverApp = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</BrowserRouter>
</StaticRouter>
);
if (context.url) {
res.redirect(context.url);
} else {
res.status(200).send(`
<!DOCTYPE html>
<html>
<head>
<title>React SSR Example</title>
</head>
<body>
<div id="root">${serverApp}</div>
<script src="/bundle.js"></script>
</body>
</html>
`);
}
});
server.listen(8000, () => {
console.log('Server is listening on port 8000');
});
Output:
StaticRouterProvider in React Router
React Router, a prominent library for handling routing in React applications, includes a vital component known as StaticRouterProvider.
This article aims to shed light on the functionality and importance of StaticRouterProvider, particularly in scenarios involving server-side rendering (SSR) with React applications.
Table of Content
- Understanding StaticRouterProvider
- Features of StaticRouterProvider
- Steps to implement StaticRouterProvider
- Example of StaticRouterProvider
- Conclusion
Contact Us