Part 2 — React and React Router

In part 1 we created only one component — App.jsx. Now, we need to make a component for each element we want to render to to our app. We’ll create the following components in Part 2: About.jsx, Contact.jsx, Login.jsx, Signup.jsx, Header.jsx, Footer.jsx, and Searchbar.jsx.

Create a “Components” folder. In that folder, create files for each of the components mentioned above. Components must render something. In other words, the return can not be empty so for now we’ll add some placeholder text.

In the About.jsx file declare a class component. In its render function declare a div that renders the text “About Page”. Do the same for the Contact, Signup, Searchbar, and Login components.

Contact.jsx

Similarly, declare a class in the header component. In its render function declare a div with a ul tag that nests li tags for each menu button we want to have. You can also add a header tag with a title for your homepage. You can style the menu items however you like (as buttons, or icons, or simply text).

I’ve decided to place the signup button in the Login component instead of in the Header. You can leave your signup in the Header if you choose!

Add text or a ul tag (whichever you want to render) to your footer component.

Header.jsx

Now that our components are set up we can add navigation to each menu item. So that when a user clicks the About button in the header, About.jsx will render.

To enable react router we will use Route and Link tags. To start, we’ll need to make some changes to the index.js file.

First, import each component we plan to add navigation to — each button in our menu bar (about, contact, login, signup).

Next declare a function — we’ll call it “routing”. In this function we’ll declare the Browser Router tag from react-router. Within the BrowserRouter tag, define a div that nests Route tags for each component in the menu bar. In each Route tag we’ll define the path we want the button to lead to and the component that should render when the button is clicked.

In the render method replace <App/> with our routing function. We are now hanging this function to the root element. Because of this we need to include a path to “/” in our routing function that renders the App component.

Now that our Route’s are set up we can declare their matching Link’s.

In Header.jsx add Link tags each li element you created earlier. In each Link tag define the “to” attribute with the corresponding paths we created in the index.js file.

Header.jsx revised
Login.jsx

Now when you click any of these elements they will lead to the path you’ve created and render the component attached to that path.

Congratulations! In part 2 you have successfully used React Router!

In the next section we’ll go over the functionality for the search bar, pulling data from an API and pulling data from local storage.

Let me know if you have any questions or comments!

-> Continue to part 2 now!

--

--