Skip to content

Instantly share code, notes, and snippets.

@mhuggins
Last active October 25, 2019 10:10
Show Gist options
  • Save mhuggins/96aaee75d5d783da142c5cdead851c06 to your computer and use it in GitHub Desktop.
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
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);
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>
);
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;
@rmlzy
Copy link

rmlzy commented Jan 29, 2019

Thank you man, you saved my life

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment