I've got react-router
4.0.0-alpha.4 installed in my React project, which is a tutorial that I'm following, and I'm having a really difficult time understanding how it's being called in StorePicker.jsx
App.jsx
import React from 'react';
import { render } from 'react-dom';
import './css/style.css';
import {BrowserRouter, Match, Miss} from 'react-router';
import StorePicker from './components/StorePicker';
import App from './components/App';
import NotFound from './components/NotFound';
const Root = () => {
return(
<BrowserRouter>
<div>
<Match exactly pattern="/" component={StorePicker}/>
<Match pattern="/store/:storeId" component={App}/>
<Miss component={NotFound}/>
</div>
</BrowserRouter>
)
}
render(<Root/>, document.querySelector('#main'));
So towards the end in StorePicker.jsx
I create a contextTypes
property on the StorePicker
object. I then set the value equal to { router: React.PropTypes.object }
. React.PropTypes.object
has nothing to do with the router though.
But in goToStore(event)
all of a sudden the router
object is available in this.context.router
.
Where did this come from? Is it because the word
router
is a special keyword when I use it incontextTypes
, andReact.PropTypes.object
somehow knows to fetch the router object as a result and add it tothis.context
?Why is this tutorial even telling me to use this pattern? According to the React docs,
context
should be avoided: https://facebook.github.io/react/docs/context.htmlIs there a better way to do this?
StorePicker.jsx
import React from 'react';
import { getFunName } from '../helpers.js'
class StorePicker extends React.Component{
goToStore(event){
event.preventDefault();
const storeId = "1234";
this.context.router.transitionTo(`/store/${storeId}`);
}
render(){
return (
<button onClick={(e) => this.goToStore(e)}>CLICK ME</button>
)
}
};
StorePicker.contextTypes = {
router: React.PropTypes.object
}
export default StorePicker;
The code from this tutorial works, but I have no idea why it's working.