Как установить router react

Installation

This document describes the most common ways people use React Router with various tools in the React Ecosystem.

Basic Installation

Most modern React projects manage their dependencies using a package manager like npm or Yarn. To add React Router to an existing project, the first thing you should do is install the necessary dependencies with the tool of your choice:

Create React App

Follow the instructions in the React documentation to set up a new project with Create React App, then follow the installation instructions above to install React Router in your project.

Once your project is set up and React Router is installed as a dependency, open the src/index.js in your text editor. Import BrowserRouter from react-router-dom near the top of your file and wrap your app in a
:

Now you can use React Router anywhere in your app! For a simple example, open src/App.js and replace the default markup with some routes:

When it’s time to deploy your app to production, be sure to follow Create React App’s instructions on deploying with React Router to be sure your server is configured correctly.

Parcel

Follow the instructions in the Parcel documentation to set up a new project, then follow the installation instructions above to install React Router in your project.

Now that React and React Router are set up create a new file App.js and add some routes and components:

Webpack

Follow the instructions in the webpack documentation to set up a new project, then follow the installation instructions above to install React Router in your project.

Setting up a new React project in webpack is a bit more involved than Parcel or Create React App. Because webpack is a low-level tool that allows you to fine-tune your build to your liking, you may want to read the webpack documentation or check out webpack configurations in other repos to understand how to build your own.

HTML Script Tags

One of the quickest ways to add React and React Router to a website is to use good ol’

Источник

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

Данный материал является частью цикла статей «Создаем приложение на React с использованием Redux». Не забудьте посмотреть другие статьи по этой теме 🙂

Настройка React Routing, BrowserRouter и Route

Чтобы начать React Routing, нам нужно установить React Router, выполнив эту команду в окне терминала:

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

После завершения установки изменим файл App.js для поддержки маршрутизации React:

Компонент Switch отображает первого дочернего элемента, который соответствует местоположению. Как только он находит подходящий маршрут, он прекращает поиск другого.

Меню навигации

Теперь, когда маршрутизация настроена, давайте создадим меню навигации.

Внутри папки компонентов создайте новую папку и назовите ее «Навигация». Внутри создайте два файла : Navigation.js и Navigation.css :

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

Мы собираемся использовать элемент навигации Bootstrap для создания нашей собственной навигации. Перед созданием компонента давайте установим еще одну библиотеку, в которой React должен объединить навигацию Bootstrap с навигацией React-Router:

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

Теперь изменим файл Navigation.js :

Описание кода меню навигации

В качестве продолжения нам нужно сначала изменить файл Navigation.css :

И чтобы включить этот компонент навигации в компонент Layout :

В результате мы можем увидеть наше меню навигации:

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

​​Создание компонента «Не найдено»

Мы собираемся добавить еще одну функцию, чтобы завершить эту часть сообщения. Каждый раз, когда пользователь вводит несуществующий URL-адрес, приложение перенаправляет его или ее на компонент не найден (404).

Во-первых, давайте создадим новую папку внутри папки компонентов и назовем ее ErrorPages. Внутри создайте новую папку с именем NotFound. Там создайте два новых файла NotFound.js и NotFound.css :

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

Теперь изменим файл NotFound.js :

Затем нам нужно изменить файл NotFound.css :

Наконец, давайте изменим файл App.js :

Благодаря этому изменению всякий раз, когда пользователь вводит несуществующий URL-адрес, наше приложение будет отображать компонент NotFound (даже если мы введем localhost: 3000/404)

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

Заключение

Мы успешно завершили навигационную часть серии.

Прочитав этот пост, вы узнали:

Спасибо, что прочитали статью, и я надеюсь, что вы нашли в ней что-то полезное.

В следующей части серии мы узнаем, как подготовить HTTP-репозиторий с помощью Axios и Redux.

Источник

Overview

If you’re familiar with the JavaScript ecosystem, React, and React Router, this serves as a quick overview of React Router v6 with lots of code and minimal explanations.

Installation

Configuring Routes

In previous versions of React Router you had to order your routes a certain way to get the right one to render when multiple routes matched an ambiguous URL. V6 is a lot smarter and will pick the most specific match so you don’t have to worry about that anymore. For example, the URL /teams/new matches both of these route:

Navigation

Use Link to let the user change the URL or useNavigate to do it yourself (like after form submissions):

Reading URL Parameters

Use :style syntax in your route path and useParams() to read them:

Note that the path segment :invoiceId and the param’s key params.invoiceId match up.

A very common use-case is fetching data when the component renders:

Nested Routes

This is one of the most powerful features of React Router making it so you don’t have to mess around with complicated layout code. The vast majority of your layouts are coupled to segments of the URL and React Router embraces this fully.

Routes can be nested inside one another, and their paths will nest too (child inheriting the parent).

This route config defined three route paths:

When the URL is «/invoices/sent» the component tree will be:

The nested url segments map to nested component trees. This is perfect for creating UI that has persistent navigation in layouts with an inner section that changes with the URL. If you look around the web you’ll notice many websites (and especially web apps) have multiple levels of layout nesting.

Here’s another example of a root layout with navigation that persists while the inner page swaps out with the URL:

Index Routes

Index routes can be thought of as «default child routes». When a parent route has multiple children, but the URL is just at the parent’s path, you probably want to render something into the outlet.

Consider this example:

This page looks great at «/invoices» and «/activity», but at «/» it’s just a blank page in because there is no child route to render there. For this we can add an index route:

You can have an index route at any level of the route hierarchy that will render when the parent matches but none of its other children do.

Relative Links

«Not Found» Routes

Multiple Sets of Routes

Although you should only ever have a single in an app, you may have as many as you need, wherever you need them. Each element operates independently of the others and picks a child route to render.

Descendant

And that’s just about it! We haven’t covered every API here, but these are definitely the most common ones you’ll use. If you’d like to learn more, go ahead and follow our tutorial or browse the full API reference.

React Router is built and maintained by Remix and hundreds of contributors.

Источник

Tutorial

Introduction

React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces. React Router runs anywhere React runs; on the web, on the server with node.js, and on React Native.

If you’re just getting started with React generally, we recommend you follow the excellent Getting Started guide in the official docs. There is plenty of information there to get you up and running. React Router is compatible with React >= 16.8.

We’ll keep this tutorial quick and to the point. By the end you’ll know the APIs you deal with day-to-day with React Router. After that, you can dig into some of the other docs to get a deeper understanding.

While building a little bookkeeping app we’ll cover:

Installation

Recommended: StackBlitz

To do this tutorial you’ll need a working React app. We recommend skipping bundlers and using this demo on StackBlitz to code along in your browser:

Как установить router react. Смотреть фото Как установить router react. Смотреть картинку Как установить router react. Картинка про Как установить router react. Фото Как установить router react

As you edit files, the tutorial will update live.

Using a bundler

Feel free to use your bundler of choice like Create React App or Vite.

Then install React Router dependencies:

Then edit your App.js to be pretty boring:

Actually, that «!» doesn’t look boring at all. This is pretty exciting. We sat on React Router v6 beta for over a year as we shifted gears with our business after a global pandemic. THIS IS THE MOST EXCITING THING WE’VE DONE IN A WHILE!

Finally, go make sure index.js or main.jsx (depending on the bundler you used) is actually boring:

Finally, start your app:

Connect the URL

First things first, we want to connect your app to the browser’s URL: import BrowserRouter and render it around your whole app.

Nothing changes in your app, but now we’re ready to start messing with the URL.

Add Some Links

Go ahead and click the links and the back/forward button (if you’re using StackBlitz, you’ll need to click the «Open in New Window» button in the inline-browser’s toolbar). React Router is now controlling the URL!

We don’t have any routes that render when the URL changes yet, but Link is changing the URL without causing a full page reload.

Add Some Routes

Add a couple new files:

(The location of the files doesn’t matter, but when you decide you’d like an automatic backend API, server rendering, code splitting bundler and more for this app, naming your files like this way makes it easy to port this app to our other project, Remix 😉)

Now fill ’em up with some code:

Remember if you’re using StackBlitz to click the «Open in New Window» button in the inline browser’s toolbar to be able to click the back/forward buttons in your browser.

Nested Routes

You may have noticed when clicking the links that the layout in App disappears. Repeating shared layouts is a pain in the neck. We’ve learned that most UI is a series of nested layouts that almost always map to segments of the URL so this idea is baked right in to React Router.

Let’s get some automatic, persistent layout handling by doing just two things:

First let’s nest the routes. Right now the expenses and invoices routes are siblings to the app, we want to make them children of the app route:

When routes have children it does two things:

However, before (2) will work we need to render an Outlet in the App.jsx «parent» route.

Now click around again. The parent route ( App.js ) persists while the swaps between the two child routes ( and )!

As we’ll see later, this works at any level of the route hierarchy and is incredibly powerful.

Listing the Invoices

Normally you’d be fetching data from a server somewhere, but for this tutorial let’s hard code some fake stuff so we can focus on routing.

Make a file at src/data.js and copy/paste this in there:

Cool! Now click an invoice link and see what happens.

Adding a «No Match» Route

Before we move on, it’s good practice to always handle this «no match» case. Go back to your route config and add this:

The «*» has special meaning here. It will match only when no other routes do.

Reading URL Params

Let’s define a route that will match these kinds of URLs and enable us to get the invoice number from it.

Create a new inside of the «invoices» route like this:

A couple things to note:

Alright, now go click a link to an invoice, note that the URL changes but the new invoice component doesn’t show up yet. Do you know why?

That’s right! We need to add an outlet to the parent layout route (we’re really proud of you).

Okay, let’s close the circle here. Open up the invoice component again and let’s get the :invoiceId param from the URL:

Note that the key of the param on the params object is the same as the dynamic segment in the route path:

Let’s use that information to build up a more interesting invoice page. Open up src/data.js and add a new function to lookup invoices by their number:

And now back in invoice.jsx we use the param to look up an invoice and display more information:

Index Routes

Index routes are possibly the most difficult concept in React Router for people to understand. So if you’ve struggled before, we hope this can clarify it for you.

Right now you’re probably looking at one of the invoices. Click on the «Invoices» link in the global nav of your app. Notice that the main content area goes blank! We can fix this with an «index» route.

Sweet! Now the index route fills the empty space!

Maybe you’re still scratching your head. There are a few ways we try to answer the question «what is an index route?». Hopefully one of these sticks for you:

Active Links

We did three things there:

You can do the same thing with className on NavLink :

Search Params

Let’s see it in action by adding a little filter on the invoices nav list.

Check this out, as the user types:

Custom Behavior

If you filter the list and then click a link, you’ll notice that the list is no longer filtered and the search param is cleared from the and the URL. You might want this, you might not! Maybe you want to keep the list filtered and keep the param in the URL.

We can persist the query string when we click a link by adding it to the link’s href. We’ll do that by composing NavLink and useLocation from React Router into our own QueryNavLink (maybe there’s a better name, but that’s what we’re going with today).

You can put that code anywhere you want in your app and then replace your NavLink in src/routes/invoices.jsx with QueryNavLink and you’re done.

With that information, the task in QueryNavLink is pretty simple: add the location.search onto the to prop. You might be thinking, «Geez, seems like this should be a built-in component of React Router or something?». Well, let’s look at another example.

What if you had links like this on an ecommerce site.

And then you wanted to style them as «active» when the url search params match the brand? You could make a component that does exactly that pretty quickly with stuff you’ve learned in this tutorial:

Or maybe you want the links to be additive (clicking Nike and then Vans adds both brands to the search params) instead of replacing the brand:

Or maybe you want it to add the brand if it’s not there already and remove it if it’s clicked again!

As you can see, even in this fairly simple example there are a lot of valid behaviors you might want. React Router doesn’t try to solve every use-case we’ve ever heard of directly. Instead, we give you the components and hooks to compose whatever behavior you need.

Navigating Programmatically

Okay, back to our app. Hang in there, you’re almost done!

Most of the time the URL changes is in response to the user clicking a link. But sometimes you, the programmer, want to change the URL. A very common use case is after a data update like creating or deleting a record.

Let’s add a button that marks the invoice as paid and then navigates to the index route.

First you can copy and paste this function that deletes an invoice from our fake data store:

Now let’s add the delete button, call our new function, and navigate to the index route:

Getting Help

Congrats! You’re all done with this tutorial. We hope it helped you get your bearings with React Router.

If you’re having trouble, check out the Resources page to get help. Good luck!

React Router is built and maintained by Remix and hundreds of contributors.

Источник

React Router Dom V4 Маршрутизация

В этом уроке мы познакомимся с библиотекой react-router-dom, которая используется в многостраничных приложениях для маршрутизации. Рассмотрим такие составляющие как Router, Link, NavLink, Route, Switch, Redirect, History, включенные в библиотеку react-router-dom. Наиболее подходящим способом увидеть, как работает React Router v4, является написание простого многостраничного приложения React с использованием новых компонентов маршрутизатора. Но сначала давайте разберемся чем новая версия v4 отличается от предыдущей версии v3.

React Router v4 и React Router v3 различия

Использование компонента Route

Использование компонента Link

React Router v4 и React Router v3 различия

До v4 была версия v3, v4 — это полностью обновленная версия, так в чем же разница между этими двумя маршрутизаторами React? Вот краткий список большинства отличий:

React Router v4 был разделен на три пакета:

Установка react-router-dom

Поскольку мы создаем web-приложение, а не мобильное приложение, нам необходимо установить пакет react-router-dom, поэтому внутри директории проекта необходимо выполнить одну из следующих команд:

Если вы используете npm, то установить можно следующей командой:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *