Sunday, August 23, 2020

React Router

So you want to do routing with your Redux app. You can use it with React Router. Redux will be the source of truth for your data and React Router will be the source of truth for your URL. In most of the cases, it is fine to have them separate unless you need to time travel and rewind actions that trigger a URL change.

Connecting React Router with Redux App

First we will need to import <Router /> and <Route /> from React Router. Here's how to do it:

import { BrowserRouter as Router, Route } from 'react-router-dom'

In a React app, usually you would wrap <Route /> in <Router /> so that when the URL changes, <Router /> will match a branch of its routes, and render their configured components. <Route /> is used to declaratively map routes to your application's component hierarchy. You would declare in path the path used in the URL and in component the single component to be rendered when the route matches the URL.

const Root = () => (

  <Router>

    <Route path="/" component={App} />

  </Router>

)

However, in our Redux App we will still need <Provider />. <Provider /> is the higher-order component provided by React Redux that lets you bind Redux to React 

We will then import the <Provider /> from React Redux:

import { Provider } from 'react-redux'

We will wrap <Router /> in <Provider /> so that route handlers can get access to the store.


const Root = ({ store }) => (

  <Provider store={store}>

    <Router>

      <Route path="/" component={App} />

    </Router>

  </Provider>

)


Now the <App /> component will be rendered if the URL matches '/'. Additionally, we will add the optional :filter? parameter to /, because we will need it further on when we try to read the parameter :filter from the URL.


<Route path="/:filter?" component={App} />

Navigating with React Router

React Router comes with a <Link /> component that lets you navigate around your application. If you want to add some styles, react-router-dom has another special <Link /> called <NavLink />, which accepts styling props. For instance, the activeStyle property lets us apply a style on the active state.

In our example, we can wrap <NavLink /> with a new container component <FilterLink /> so as to dynamically change the URL.

References:

https://redux.js.org/advanced/usage-with-react-router

No comments:

Post a Comment