In this section, we set up our router using react-router, which has become the default router for React. We're also going to create a few basic views so that our router has something to display.
We're also going to go some of the very basics of how routers work and the various routing options. For the time being, we're going to stick to a hash router (explained below).
The first thing we should do is create a few components for our router to render. For now, let's create a Home component for our root route (/) and a Settings component for our user profile and settings (/settings).
Because React allows us to reuse components, we should be as explicit as possible with our component names. At some point in the future, we will have a Message component that will be used once for every message in a chat between customer and representative, and may even be shared across applications.
For the sake of clarity, we will avoid using plural names whenever possible. Comment vs. Comments will always lead to confusion down the road. As we add more components, it will become abundantly clear why this is necessary.
We will want to keep all of these organized in a components/ directory under app/. Let's create that now along with directories and files for each of our new components. Remember, directory changes may not be included in the remainder of this course for the sake of brevity.
$ mkdir -p app/components/{Home,Settings}$ touch app/components/{Home/index.js,Settings/index.js}Note the -p flag in our mkdir command. This tells bash that if the directory does not exist, go ahead and make it. If we did not use this, we would have to run mkdir app/components first.
And while we're at it, let's create some generic content in each of those index.js files we just created.
import React from "react"export class Home extends React.Component { render() { return <div>Home component</div> }}export default Homeimport React from "react"export class Settings extends React.Component { render() { return <div>Settings component</div> }}export default SettingsWe are going to use the popular React Router for our routing. If you are not familiar with what routing is, it's the thing that handles your url path, such as http://github.com/learnphoenix, and directs you to the proper view. Without a router, your app will be limited to a single page (this is not strictly true as there are ways around using a router, but this is generally true).
Now that we have a few components set up, we should direct our router to access them. In order to use React Router, we need to add a few dependencies.
$ npm install --save history react-routerReact Router requires the history package and does not automatically install it for you.
The next thing we need to do is change the index.js file within our app directory to use our router. Rather than use ReactDOM to directly render directly to the DOM, we're going to go through React Router to render the appropriate content based on the current path.
Add the following code the index.js file at the root of your project. Each line will be described in detail after the code block.
import React from "react"import ReactDOM from "react-dom"import { Router, Route, IndexRoute, hashHistory } from "react-router"import { default as Home } from "./components/Home"import { default as Settings } from "./components/Settings"const App = props => <div>{props.children}</div>ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="settings" component={Settings} /> </Route> </Router>, document.getElementById("root"))The first thing we have here is a list of our dependencies for this file. React and ReactDOM should look familiar. From react-router, we need Router, Route, and IndexRoute. The Router is the outer element that controls our routes, Route is each individual route, and IndexRoute displays a component when you get to the / root route.
Also, since we're exporting both a named export (export class Home ...) and a default export (export default Home), we are specifying that we are importing the default import using the syntax { default as ... }. This is not strictly necessary, and your app will not throw an error, but it's the recommended syntax as of July 2016.
A note on ES2016 arrow function syntax: We've also (temporarily) changed around our App component to show of the different ways in which you can write functions in ES2015. When writing arrow functions in ES2015:
In other words, all the following are equivalent:
const App = function (props) { return <div>{props.children}</div>}.bind(this)const App = props => { return <div>{props.children}</div>}const App = props => { return <div>{props.children}</div>}const App = props => <div>{props.children}</div>const App = ({ children }) => <div>{children}</div>The hashHistory bit is something that React Router is using to create URLs. It does not require server-side configuration, so it is ideal for single page apps like this one. Eventually we might want to change this over to browserHistory, but we will hold off on that until we deal with server-side rendering and other options that require us to run our frontend through a server.
Then we import the three components we just made so they can be rendered by the router when the user hits the relevant url.
The next thing we need to do is create a an App component that holds all of our other components. Anything in this component will be rendered in every view, so use it sparingly. Within this component, we render all of the child components as we define in our router below.
The last thing we need to do is set up our routes. You should be able to see a pretty obvious hierarchy of routes, with the App component holding each of two child components(Home, Settings) each of which has its own path.
So now, if you go to localhost:3000, you should see your Home component. If you go to localhost:3000/#/settings, you should see your settings component.
There are a few things to note about hashHistory. Your routes will all have a # in them. So if you want to view the settings, it will be accessible at localhost:3000/#/settings rather than just localhost:3000/settings.
What's actually happening under the hood is there is an event listener that listens for a change in the url, and whenever it changes, it triggers a function. When you enter a url, your server ignores anything that comes after a # by default. This is because data after a hash (referred to as a fragment) is generally used to change things only on the client; it is often used to set scroll position.
You can try this out if you want by typing in https://github.com/#learnphoenix. You'll notice that what you actually see is the GitHub homepage. This is because when you make a request to a particular url (e.g. https://github.com/learnphoenix), you're sending a message to the server that says, "give me the data I need for github.com from the /learnphoenix route", but when you use a hash router, the server is only asked for github.com and the client handles the routing for everything after the hash (#) using react-router.
There is also some random stuff that gets put on the end of your url, such as _k=vm23gw. This is for people who are using an older browser that does not support the HTML5 push API. This is not strictly necessary and can be disabled if you are not worried about supporting old browsers.
It's actually really easy to create your own basic router. All you have to do is listen for changes in your url path and run a function that renders a new view when a particular route is hit. There's nothing magical about routers; try running window.location in your browser console to see what you have access to. That said, there are many additional features and edge cases that make using something like react-router more practical.