< Previous: How to Add a New Route to React Router   Next: Making Custom URLs with React Router Params >

Creating a Link Between Pages in React Router

We need a way to link users from our List page to our Detail page, but we're not going to do what you're probably thinking. See, an experienced web developer like you will have written <a href="/foobar">Click here!</a> more times than you can remember, and you probably think we should do something similar here.

Well, we're not, because React Router has a better solution: the <Link> component. This is a wrapper around our old friend the HTML anchor, but has the added benefit that it automatically knows where your components are and can adjust the style of a link to make it look active when it's the page the user is currently browsing.

That "automatically knows where your components are" part is important. Remember, all our pages start with /#/ right now. If you tried to write <a href="/react">View React Commits</a> it would point to /react rather than /#/react, and so wouldn't work. React Router's <Link> component fixes that automatically.

So, we're going to change List.js so that it contains a React Router link to the Detail page. This means importing Link from React Router, then using it, which is trivial to do.

Here's the new and improved List.js:


import React from 'react';
import { Link } from 'react-router';

class List extends React.Component {
    render() {
        return (
                <p>Please choose a repository from the list below.</p>
                    <li><Link to="/react">React</Link></li>

export default List;

Even though we're linking to /react, that gets silently rewritten by React Router to be /#/react, which means our current URLs all carry on working correctly. It also means that if you change your server configuration so the whole /#/ isn't needed any more, those links will automatically update.

The new List page uses a React Router Link component to navigate to our Detail page.

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!

< Previous: How to Add a New Route to React Router   Next: Making Custom URLs with React Router Params >

Copyright ©2016 Paul Hudson. Follow me: @twostraws.