Objective: To create routes in React.
Creating the React App
We're going to look at how to create routes in React. The first thing we're going to do is to create a new React app. In this example, I created a new GitHub repository and cloned it in a folder. So at this point, the only thing in my project's folder is a .gitignore file and a README file.
To create the React starter package, cd into your project's folder and run npx create-react-app my-app (where my-app is replaced with the name of your app). You can also run npx create-react-app . instead of npx create-react-app my-app. Adding the dot (instead of creating a name) will create and set up all the initial React library files in the current folder. In this example, I'll be running npx create-react-app .
npx create-react-app .
So, once you've done that and get the "Happy hacking!" message in the terminal, you're all set to go.
And now your project's folder should look like this:
To start our React app, we need to go into the root of our project folder and run npm start (or yarn start).
npm start
And this is what we should see. We now have our React app running in the browser. So, now that we have our React app running, let's create our routes.
Creating the Routes
1. Let's start by getting rid of some things we don't need, just to keep things simple. Right now, our App.js file looks like this. This is what it looks like when we create a new React app:
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Let's get rid of everything but the <div>, and we'll put an <h1> inside with "Hello". And we'll get rid of the logo that was imported above too. And we can just leave the CSS as it is (line 2). So, our App.js should now look like this:
import React from 'react';
import './App.css';
function App() {
return (
<div className='App'>
<h1>Hello</h1>
</div>
);
}
export default App;
And now our app should look like this in the browser:
2. So, now we're ready to work on our routes. The first thing we need to do is to install react-router-dom. So, let's go ahead and install it: npm i react-router-dom.
npm i react-router-dom
And we can verify that it has been installed by checking in the dependencies in our package.json file (line 7).
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1"
},
3. We're going to be using React Router, so let's set that up. Let's start by importing it into our App.js file (line 2).
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import './App.css';
And then, let's go down to where we have our main app and wrap everything inside of <Router> (after the return, and before the <div>).
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import './App.css';
function App() {
return (
<Router>
<div className='App'>
<h1>Hello</h1>
</div>
</Router>
);
}
export default App;
And let's go ahead and add some routes now. First, let's add a <Switch> (after the <div>). And we can get rid of our <h1> now. And inside the <Switch> is where we're going to put our routes. So, let's add a route for the Home Page ('/'), and another one for an About Page ('/about') (lines 6-7). And at this point we're going to get a couple of errors saying, 'Home' is not defined and 'About' is not defined, and we're not going to see anything in the browser. And that's because we haven't created these components. So, let's go ahead and do that now.
function App() {
return (
<Router>
<div className='App'>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/about' component={About} />
</Switch>
</div>
</Router>
);
}
4. So, let's create these components, so that we'll be able to go to the actual page when we go to their URLs ('/' and '/about'). To do this, let's go inside our src folder and create a folder called components. And inside components, we'll create another folder called pages. This is where we're going to keep our Home Page and About Page components. So, inside the pages folder, we'll create two separate files: Home.js and About.js. And these will be our components.
Next, we need to go to App.js and bring these in (lines 3-4).
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/pages/Home';
import About from './components/pages/About';
import './App.css';
So, now that we've brought our components into App.js, we need to add some code to our components so that we'll be able to see something in the browser. And this is where you would put your content and other components (e.g. forms, images, text, etc.), depending on what you're building. But for our purposes, we'll just have an <h1> (line 6). So, we need to bring in React (line 1), and then we'll go ahead and create our component, with our <h1>. And then we need our export default at the end (line 11).
import React from 'react';
const Home = () => {
return (
<div>
<h1>Home Page</h1>
</div>
);
};
export default Home;
And when we go to the browser, we get our Home Page with our <h1>.
And remember, the path we used for the Home Page was '/', so when we look at the URL, it's just going to be localhost:3000/.
And let's do the same for the About Page. And we'll just have an <h1> with the text, "About Page".
import React from 'react';
const About = () => {
return (
<div>
<h1>About Page</h1>
</div>
);
};
export default About;
And the path we're using for the About Page is /about. So, now when we go to /about in our URL, we should see our About Page. And we get our <h1>.
And you can see that the URL now shows /about, which means we're on the About Page.
5. Okay. So, we've got our routes set up and our Home and About pages. But it doesn't do us any good if we have to manually type in the paths in order to get to our pages, so let's add some links so we can get to our pages by clicking on them. And normally, you would have a navbar for your links, but to keep things simple, we'll just use links. So, let's go to our Home Page component (Home.js). And the first thing we need to do is to bring in Link from react-router-dom (line 2). And we're going to put each of our links in an <li>. And each link is going to point to a specific path, depending on the page (lines 8-13).
import React from 'react';
import { Link } from 'react-router-dom';
const About = () => {
return (
<div>
<h1>About Page</h1>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/about'>About</Link>
</li>
</div>
);
};
export default About;
And if we check the browser, we should get our links.
And we'll do the same with the About Page.
import React from 'react';
import { Link } from 'react-router-dom';
const About = () => {
return (
<div>
<h1>About Page</h1>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/about'>About</Link>
</li>
</div>
);
};
export default About;
And we should see our links on the About Page as well. And the links should be working now. So, now we can easily navigate to our Home and About pages by just clicking on the links. And when you check the URL, you should see the correct path, depending on which page you're on.
6. The last thing left to do is to create an error page. And we're going to be creating this component as well, just like we did for the Home and About pages. Let's first go to App.js and add this route. And we'll name the component Error (line 8). And you'll notice that this route looks a little different from the other routes. For Home and About, we need the exact path, since there is only one exact path for each page. However, the reason we're using an error page, is so that we can have a page that a user is redirected to if they do not hit one of our exact paths (e.g. due to misspelling issues, or broken or dead links). That's why we do not use exact path for our Error Page route.
function App() {
return (
<Router>
<div className='App'>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/about' component={About} />
<Route component={Error} />
</Switch>
</div>
</Router>
);
}
And we also need to bring in our
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Error from './components/pages/Error';
import './App.css';
So, inside of our pages folder, let's create a file called Error.js. And we'll just add in a simple page, just like we did for our Home and About components. And we'll add an <h1> with a message like, "404 Page Not Found."
import React from 'react';
const Error = () => {
return (
<div>
<h1>404 Page Not Found.</h1>
</div>
);
};
export default Error;
And we'll go ahead and add a link so that the user will be able to get back to the Home Page (line 9). And then we need to remember to import Link (line 2).
import React from 'react';
import { Link } from 'react-router-dom';
const Error = () => {
return (
<div>
<h1>404 Page Not Found.</h1>
<li>
<Link to='/'>Home</Link>
</li>
</div>
);
};
export default Error;
So, we now have our Error Page set up. But we're not going to see it unless we do not hit our Home and About paths exactly. So let's say, for example, we have an extra letter in our URL, for some reason, so that it looks like this.
Well, this is not one of our paths. We're trying to get to our About Page, but we're not hitting the exact path. So, since we're not hitting the exact path, we're redirected to the Error Page. And we get our error message, "404 Page Not Found." And there's our link to the Home Page. So, if we click on it, we're back on our Home Page.
And we're back on our Home Page.
So, we created a simple React app with working routes. We started by creating a new React app. Next, we created our routes for a Home and About page. Then, we created the Home and About components. Finally, we created an Error Page for users to get redirected to if they do not hit one of our exact paths, with a link that takes us back to the Home Page.