Redux: Navigating with React Router <Link>

Dan Abramov
InstructorDan Abramov
Share this video with your friends

Social Share Links

Send Tweet

We will learn how to change the address bar using a <Link> component from React Router.

[00:00] The links that control the visibility filter do not currently behave like real links. I'd like to change it so that the background works and the current URL updates when I click on these links and change the current visibility filter.

[00:16] I will add a parameter to my route called filter, and I need to wrap it in parens to tell React Router that it's optional, because if it's not specified, I want to show all todos.

[00:28] Now I'm opening the footer component that displays the links. Right now, I'm using the custom convention for the filter prop, but I'm going to change this to align more closely with the paths I want to be displayed, so I'm using "active" and "completed" for the active and completed paths, and to avoid passing an empty string, I'll just use a null string to signify the default path.

[00:52] My current implementation of the filter link component dispatches an action every time it's clicked, and reads its active state from the store, comparing its filter prop to the visibility filter in the store.

[01:06] However, I'm not going to need this implementation anymore because I want the router to be in control of any state that is in the URL. This is why I import link from React Router, and my new implementation of the filter link component is going to use it.

[01:24] It accepts filter as a prop, and it renders through the link provided by React Router. Its true prop corresponds to the path that we want the link to point to, so if the filter is "all," we're going to use the root path. Otherwise, we'll just use the filter itself as the path.

[01:43] I am also specifying the active style prop so that the link is styled differently when its true prop matches the current path. Finally, I'm passing children to the link itself, and I'm adding children as a prop to filter link so that the parent component can specify the children.

[02:02] Now I'm exporting filter link, and I have some cleanup to do. I can remove the set visibility filter action-creator, as I don't use it anymore. I can also remove my custom link component, because now I'm using the link from React Router instead of it.

[02:19] If I run the app now, clicking on the link will update the URL bar. It also works in the other direction. Clicking on the back or forward buttons gets the corresponding link active.

[02:31] In the next lesson, we will teach our component to read the current filter from the URL instead of Redux store.