We'll create a Router component that would wrap our application and manage all URLs related state. We'll see how we can use React's built in context mechanism-pass data and functions between components without have t O Pass props all the through to the component tree.
// Index.js Reactdom.render ( <MuiThemeProvider> <router><app/></router></ Muithemeprovider>, document.getElementById ('root'));
On the top level, we add Router component to wrap our App component.
ExportclassRouter extends Component { state={Route:getcurrentpath ()}; Handlelinkclick= (route) = = { This. SetState ({route}); History.pushstate (NULL,"', route); }; Static Childcontexttypes={route:React.PropTypes.string, LinkHandler:React.PropTypes.func}; Getchildcontext () { return{route: This. State.route, Linkhandler: This. Handlelinkclick}; } render () {return ( <div>{ This.props.children}</div> ); }}
We need to pass the props to the children so, Link component can know current URL state. To does this, we using ' Context ' instead of ' passing the props down to children '.
Becasue there is, problems with this. One, in a complex app, which could potentially mean passing the same item down many levels. This could mean a lot of maintenance if things need to the change.
The second problem is and in this setup, the app is being placed inside the router through a call to This.props.children. We can ' t just add props onto the app component in our render function. The "we ' re going to handle" is through React ' s context mechanism.
Import React, {Component} from 'react';ConstStyles ={padding:'8px'};exportclassLink extends Component { static contexttypes = {route:React.PropTypes. string , linkHandler:React.PropTypes.func}; Render () {ConstActiveclass = This.Context. route = = = This. props.to?'Active':"'; ConstHandleclick = (ev) = ={ev.preventdefault (); This.Context. Linkhandler ( This. props.to); }; return ( <a href="#"Style={styles} Classname={activeclass} onclick={handleclick}>{ This.props.children}</a> ); }}link.proptypes={to:React.PropTypes.string. isrequired};
Last, on the Link component, we can use the Context to access and the defined for Router compoent.
[React] Use React Context to Manage application state Through Routes