Last active
October 25, 2019 10:10
-
-
Save mhuggins/96aaee75d5d783da142c5cdead851c06 to your computer and use it in GitHub Desktop.
Higher-order component for rendering server-side status codes with react-router v4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from "express"; | |
import { renderToString } from "react-dom/server"; | |
import { StaticRouter } from "react-router-dom"; | |
import routes from "./routes"; | |
const app = express(); | |
app.use((req, res) => { | |
const context = {}; | |
const html = renderToString( | |
<StaticRouter location={req.url} context={context}> | |
{routes} | |
</StaticRouter> | |
); | |
if (context.url) { | |
res.redirect(302, context.url); | |
} else { | |
const status = context.status || 200; | |
res.status(status).type("html").end(renderServerHTML(html)); | |
} | |
}); | |
app.listen(process.env.PORT || 80); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { Route, Switch } from "react-router-dom"; | |
const Dashboard = () => { | |
return <div>Welcome</div>; | |
}; | |
const NoMatch = () => { | |
return <div>Not found</div>; | |
}; | |
export default ( | |
<Layout> | |
<Switch> | |
<Route exact path="/" component={Dashboard} /> | |
<Route component={withStatus(404)(NoMatch)} /> | |
</Switch> | |
</Layout> | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import PropTypes from "prop-types"; | |
import { withRouter } from "react-router-dom"; | |
const { object, shape } = PropTypes; | |
const withStatus = (statusCode) => (MyComponent) => { | |
class StatusComponent extends Component { | |
static displayName = `withStatus(${MyComponent.displayName || MyComponent.name})`; | |
static contextTypes = { | |
router: shape({ staticContext: object }).isRequired | |
}; | |
componentWillMount = () => { | |
const { staticContext } = this.context.router; | |
if (staticContext) { | |
staticContext.status = statusCode; | |
} | |
} | |
render = () => { | |
return <MyComponent {...this.props} />; | |
} | |
} | |
return withRouter(StatusComponent); | |
}; | |
export default withStatus; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you man, you saved my life