I am looking at the redux-blog-example. There is SignupRoute.js
which looks like this:
@connect(state => ({
auth: state.auth
}), {
signup
})
export default class SignupRoute extends React.Component {
static contextTypes = {
router: React.PropTypes.object
}
handleSubmit = (email, password) => {
const router = this.context.router;
this.props.signup(email, password, router);
}
render() {
return (
<Signup
auth={this.props}
handleSubmit={this.handleSubmit}
/>
);
}
}
How does the router
get wired up to the context
of this class
?
React Router is used to define multiple routes in the application. When a user types a specific URL into the browser, and if this URL path matches any 'route' inside the router file, the user will be redirected to that particular route.
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. Let us create a simple application to React to understand how the React Router works.
All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history. push('/login'); } return ( <div> <h1>Hi there!
What is context in React? React's context allows you to share information to any component, by storing it in a central place and allowing access to any component that requests it (usually you are only able to pass data from parent to child via props).
It uses context
, an undocumented but quite widely implemented React feature. For a full lowdown see this article, but here's the gist of it:
let router = Router(); // just illustrating, this is not how you instantiate React router
class MyComponent extends React.Component {
static contextTypes = {
router: React.PropTypes.object
};
render(){
// By declaring context type here, and childContextTypes
// on the parent along with a function with how to get it,
// React will traverse up and look for the `router` context.
// It will then inject it into `this.context`, making it
// available here.
}
}
class Parent extends React.Component {
static childContextTypes = {
router: React.PropTypes.object
};
getChildContext(){
return {
router: this.props.router
};
}
render(){
return <MyComponent />;
}
}
ReactDOM.render(<Parent router={router} />, document.getElementById('app'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With