Vodič za reagiranje usmjerivača - Kako prikazati, preusmjeriti, prebaciti, povezati i još mnogo toga, s primjerima koda

Ako ste tek započeli s Reactom, vjerojatno još uvijek zamatate glavom oko cijelog koncepta Application Single Page.

Tradicionalno usmjeravanje funkcionira ovako: recimo da upišete /contactURL. Preglednik će poslati GET zahtjev poslužitelju, a poslužitelj će vratiti HTML stranicu kao odgovor.

No, s novom paradigmom aplikacije pojedinačne stranice, svi se zahtjevi za URL-om poslužuju pomoću klijentskog koda.

Primjenjujući ovo u kontekstu React-a, svaka će stranica biti React komponenta. React-Router odgovara URL-u i učitava komponentu za tu stranicu.

Sve se događa tako brzo i neprimjetno da korisnik u pregledniku dobije iskustvo izvorne aplikacije. Između prijelaza rute nema kričave prazne stranice.

U ovom ćete članku naučiti kako koristiti React-Router i njegove komponente za stvaranje aplikacije s jednom stranicom. Otvorite svoj omiljeni uređivač teksta i krenimo.

Postavite projekt

Izradite novi React projekt izvođenjem sljedeće naredbe.

yarn create react-app react-router-demo

Koristit ću pređu za instaliranje ovisnosti, ali možete koristiti i npm.

Dalje, instalirajmo react-router-dom.

yarn add react-router-dom

Za oblikovanje komponenata koristit ću Bulma CSS okvir. Pa dodajmo i to.

yarn add bulma

Zatim uvezite bulma.min.cssu index.jsdatoteku i očistite sav šifru iz App.jsdatoteke.

import "bulma/css/bulma.min.css";

Sad kad ste postavili projekt, krenimo s izradom nekoliko komponenata stranice.

Izrada komponenata stranice

Stvorite direktorij stranica unutar mape src gdje ćemo parkirati sve komponente stranice.

Za ovaj demo napravite tri stranice - Početna, O nama i Profil.

Zalijepite sljedeće u komponente Home i About.

// pages/Home.js import React from "react"; const Home = () => ( 

This is the Home Page

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras gravida, risus at dapibus aliquet, elit quam scelerisque tortor, nec accumsan eros nulla interdum justo. Pellentesque dignissim, sapien et congue rutrum, lorem tortor dapibus turpis, sit amet vestibulum eros mi et odio.

); export default Home;
// pages/About.js import React from "react"; const About = () => ( 

This is the About Page

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis consequat nulla ac ex consequat, in efficitur arcu congue. Nam fermentum commodo egestas.

); export default About;

Stranicu profila stvorit ćemo kasnije u članku.

Stvorite Navbar komponentu

Počnimo s izradom navigacijske trake za našu aplikaciju. Ova će komponenta koristiti komponentu iz react-router-dom.

Stvorite direktorij nazvan "komponente" unutar mape src.

// components/Navbar.js import React, { useState } from "react"; import { NavLink } from "react-router-dom"; const Navbar = () => { const [isOpen, setOpen] = useState(false); return ( {/* ... */} ); }; export default Navbar;

isOpenVarijabla stanja će se koristiti za aktiviranje izbornika na mobilnim uređajima ili tabletima.

Pa dodajmo jelovnik za hamburgere.

const Navbar = () => { const [isOpen, setOpen] = useState(false); return ( setOpen(!isOpen)} > {/* ... */} ); };

Da biste dodali vezu u izbornik, upotrijebite komponentu do react-router-dom.

NavLinkKomponenta pruža deklarativnu put za kretanje prijavu. Slična je Linkkomponenti, osim što može primijeniti aktivni stil na vezu ako je aktivna.

Da biste odredili do koje rute se krećete, upotrijebite torekvizit i prenesite naziv putanje.

activeClassNameRekvizit će dodati aktivnu klasu na link ako je trenutno aktivan.

 Home 

U pregledniku se NavLinkkomponenta prikazuje kao oznaka s hrefvrijednošću atributa koja je proslijeđena u topropu.

Također, ovdje morate navesti exactrekvizit tako da se točno podudara s URL-om.

Dodajte sve veze i dovršite Navbarkomponentu.

import React, { useState } from "react"; import { NavLink } from "react-router-dom"; const Navbar = () => { const [isOpen, setOpen] = useState(false); return ( setOpen(!isOpen)} > Home   About   Profile Log in ); }; export default Navbar; 

Ako primijetite ovdje, dodao sam gumb za prijavu. Ponovno ćemo se vratiti Navbarkomponenti kada kasnije u vodiču razgovaramo o zaštićenim rutama.

Prikaz stranica

Sad kad je Navbarkomponenta postavljena, dodajte to na stranicu i krenimo s prikazivanjem stranica.

Budući da je navigacijska traka uobičajena komponenta na svim stranicama, umjesto pozivanja komponente u svakoj komponenti stranice, bit će bolji pristup prikazivanju Navbaru zajedničkom izgledu.

// App.js function App() { return ( {/* Render the page here */} ); }

Sada dodajte komponente stranice unutar spremnika.

// App.js function App() { return ( ); }

Ako sada provjerite rezultate, primijetit ćete da se i stranica Početna i O stranici About generiraju na stranicu. To je zato što još nismo dodali nikakvu logiku usmjeravanja.

You need to import the BrowserRouter component from React Router to add the ability to route the components. All you need to do is wrap all the page components inside of the BrowserRouter component. This will enable all the page components to have the routing logic. Perfect!

But again, nothing's going to change with the results – you are still going to see both the pages rendered. You need to render the page component only if the URL matches a particular path. That's where the Route component from React Router comes into play.

The Router component has a path prop that accepts the page's path, and the page component should be wrapped with the Router, as shown below.

So let's do the same for the Home component.

The exact prop above tells the Router component to match the path exactly. If you don't add the exact prop on the / path, it will match with all the routes starting with a / including /about.

If you go check out the results now, you'll still see both the components rendered. But, if you go to /about, you'll notice that only the About component gets rendered. You see this behavior because the router keeps matching the URL with the routes even after it had matched a route already.

We need to tell the router to stop matching further once it matches a route. This is done using the Switch component from React Router.

function App() { return ( ); }

There you go! You have successfully configured routing in your React app.

Protected Routes and Redirect

When working on Real-world applications, you will have some routes behind an authentication system. You are going to have routes or pages that can only be accessed by a logged-in user. In this section, you'll learn how to go about implementing such routes.

Please note that I'm not going to create any login form or have any back-end service authenticate the user. In a real application, you wouldn't implement authentication the way demonstrated here.

Let's create the Profile page component that should only be accessed by the authenticated user.

// pages/Profile.js import { useParams } from "react-router-dom"; const Profile = () => { const { name } = useParams(); return ( 

This is the Profile Page

{name}

Lorem ipsum dolor sit amet, consectetur adipiscing elit.{" "} Pellentesque risus mi, tempus quis placerat ut, porta nec nulla. Vestibulum rhoncus ac ex sit amet fringilla. Nullam gravida purus diam, et dictum felis venenatis efficitur. Aenean ac{" "} eleifend lacus, in mollis lectus. Donec sodales, arcu et sollicitudin porttitor, tortor urna tempor ligula, id porttitor mi magna a neque. Donec dui urna, vehicula et sem eget, facilisis sodales sem. ); };

We will grab the user's name from the URL using route parameters.

Add the Profile route into the router.

Currently the profile page can be accessed directly. So to make it an authenticated route, create a Higher-Order component (HOC) to wrap the authentication logic.

const withAuth = (Component) => { const AuthRoute = () => { const isAuth = !!localStorage.getItem("token"); // ... }; return AuthRoute; };

To determine if a user is authenticated or not, grab the authentication token that is stored in the browser when the user logs in. If the user is not authenticated, redirect the user to the Home page. The Redirect component from React Router can be used to redirect the user to another path.

const withAuth = (Component) => { const AuthRoute = () => { const isAuth = !!localStorage.getItem("token"); if (isAuth) { return ; } else { return ; } }; return AuthRoute; };

You can also pass in other user information like name and user ID using props to the wrapped component.

Next, use the withAuth HOC in the Profile component.

import withAuth from "../components/withAuth"; const Profile = () => { // ... } export default withAuth(Profile);

Now, if you try to visit /profile/JohnDoe, you will get redirected to the Home page. That's because the authentication token is not yet set in your browser storage.

Alright, so, let's return to the Navbar component and add the login and logout functionalities. When the user is authenticated, show the Logout button and when the user is not logged in show the Login button.

// components/Navbar.js const Navbar = () => { // ... return ( {/* ... */} {!isAuth ? (  Log in  ) : (  Log out  )} ); } 

When the user clicks on the login button, set a dummy token in the local storage, and redirect the user to the profile page.

But we cannot use the Redirect component in this case – we need to redirect the user programmatically. Sensitive tokens used for authentication are usually stored in cookies for security reasons.

React Router has a withRouter HOC that injects the history object in the props of the component to leverage the History API. It also passes the updated match and location props to the wrapped component.

// components/Navbar.js import { NavLink, withRouter } from "react-router-dom"; const Navbar = ({ history }) => { const isAuth = !!localStorage.getItem("token"); const loginUser = () => { localStorage.setItem("token", "some-login-token"); history.push("/profile/Vijit"); }; const logoutUser = () => { localStorage.removeItem("token"); history.push("/"); }; return ( {/* ... */} ); }; export default withRouter(Navbar);

And voilà! That's it. You have conquered the land of authenticated routes as well.

Check out the live demo here and the complete code in this repo for your reference.

Conclusion

I hope by now you have a fair idea of how client-side routing works in general and how to implement routing in React using the React Router library.

In this guide, you learned about the vital components in React Router like Route, withRouter, Link, and so on, along with some advanced concepts like authenticated routes, that are required to build an application.

Do check out the React Router docs to get a more detailed overview of each of the components.