From e27e8744f3ba1d90b54768645e43beefbe38e3ed Mon Sep 17 00:00:00 2001 From: Andre Rocha Date: Wed, 10 Oct 2018 18:40:36 -0400 Subject: [PATCH] Fix react router static router context bug (#29626) * Fix bug with StaticRouterContext * Add tests for react-router --- types/react-router/index.d.ts | 2 +- .../StaticRouter.tsx | 28 +++++++++++++------ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 97ec1ee647..ca81b0d908 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -88,7 +88,7 @@ export interface RouterProps { } export class Router extends React.Component { } -export interface StaticRouterContext { +export interface StaticRouterContext extends StaticContext { url?: string; action?: 'PUSH' | 'REPLACE'; location?: object; diff --git a/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx b/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx index 3dce9a5def..ca094ea78d 100644 --- a/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx +++ b/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx @@ -1,10 +1,8 @@ import * as React from 'react'; +import * as express from 'express'; +import { renderToString } from 'react-dom/server'; import { StaticRouter, Route } from 'react-router-dom'; -import { StaticRouterContext } from 'react-router'; - -interface StaticContext extends StaticRouterContext { - statusCode?: number; -} +import { StaticContext, StaticRouterContext } from 'react-router'; interface RouteStatusProps { statusCode: number; @@ -12,9 +10,9 @@ interface RouteStatusProps { const RouteStatus: React.SFC = (props) => ( { + render={({ staticContext }: {staticContext?: StaticContext}) => { if (staticContext) { - (staticContext as StaticContext).statusCode = props.statusCode; + staticContext.statusCode = props.statusCode; } return ( @@ -37,7 +35,7 @@ const PrintContext: React.SFC = (props) => ( ); class StaticRouterExample extends React.Component { - staticContext: StaticContext = {}; + staticContext: StaticRouterContext = {}; render() { return ( @@ -53,4 +51,18 @@ class StaticRouterExample extends React.Component { } } +const app = express(); + +app.get('*', (req, res) => { + const staticContext: StaticRouterContext = {}; + + const html = renderToString( + + (includes the RouteStatus component below e.g. for 404 errors) + + ); + + res.status(staticContext.statusCode || 200).send(html); +}); + export default StaticRouterExample;