Merge pull request #15453 from huy-nguyen/add-context-type-react-router

Add type of context for react-router and react-router-dom
This commit is contained in:
Nathan Shively-Sanders
2017-03-28 15:07:33 -07:00
committed by GitHub
4 changed files with 62 additions and 4 deletions

View File

@@ -1,6 +1,7 @@
// Type definitions for React Router 4.0
// Project: https://github.com/ReactTraining/react-router
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Huy Nguyen <https://github.com/huy-nguyen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -17,7 +18,8 @@ declare module 'react-router-dom' {
Switch,
match,
matchPath,
withRouter
withRouter,
RouterChildContext
} from 'react-router';
import * as React from 'react';
import * as H from 'history';
@@ -74,6 +76,7 @@ declare module 'react-router-dom' {
Switch,
match, // TypeScript specific, not from React Router itself
matchPath,
withRouter
withRouter,
RouterChildContext
}
}

View File

@@ -10,6 +10,7 @@
// Karol Janyst <https://github.com/LKay>
// Dovydas Navickas <https://github.com/DovydasNavickas>
// Tanguy Krotoff <https://github.com/tkrotoff>
// Huy Nguyen <https://github.com/huy-nguyen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -17,7 +18,17 @@ declare module 'react-router' {
import * as React from 'react';
import * as H from 'history';
// This is the type of the context object that will be passed down to all children of
// a `Router` component:
interface RouterChildContext<P> {
router: {
history: H.History
route: {
location: H.Location,
match: match<P>
}
}
}
interface MemoryRouterProps {
initialEntries?: H.Location[];
initialIndex?: number;
@@ -105,6 +116,7 @@ declare module 'react-router' {
Switch,
match, // TypeScript specific, not from React Router itself
matchPath,
withRouter
withRouter,
RouterChildContext
}
}

View File

@@ -0,0 +1,42 @@
import * as React from 'react';
import {
RouterChildContext,
RouteComponentProps
} from 'react-router';
import {
BrowserRouter as Router,
Route,
} from 'react-router-dom'
interface Params {
id?: string
}
type Props = RouteComponentProps<Params>
class ComponentThatUsesContext extends React.Component<Props, {}> {
static contextTypes = {
router: React.PropTypes.object.isRequired
}
context: RouterChildContext<Params>
private onClick = () => {
const {
history,
route: {
location,
match
}
} = this.context.router;
history.push('/some/url');
}
render() {
return <div/>
}
}
const Test = () => (
<Router>
<Route path='/' exact component={ComponentThatUsesContext}/>
</Router>
);
export default Test;

View File

@@ -20,6 +20,7 @@
"test/Basic.tsx",
"test/CustomLink.tsx",
"test/ModalGallery.tsx",
"test/NavigateWithContext.tsx",
"test/NoMatch.tsx",
"test/Params.tsx",
"test/PreventingTransitions.tsx",