Перейти к содержимому

Какая разница между link navlink в react router

  • автор:

Какая разница между link navlink в react router

В прошлой теме для обращения к ресурсам внутри приложения были использованы маршруты. Теперь добавим к этому приложению навигацию с помощью ссылок. Для этого изменим файл index.html следующим образом:

    Маршруты в React           

Для создания ссылки применяется объект Link, который определен в модуле react-router-dom:

const Link = ReactRouterDOM.Link;

Для определения блока навигации здесь добавлен компонент Nav:

function Nav() < return ; >

Для каждой ссылки с помощью атрибута to определяет путь перехода.

Затем компонент Nav помещается в объект Router. И после запуска мы увидим блок ссылок, по которым сможем переходить к ресурсам приложения:

Link в React

Аналогичный пример с использованием компонентов-классов:

    Маршруты в React           

Кроме объекта Link из модуля react-router-dom для создания ссылок мы можем использовать объект NavLink . Этот объект во многом аналогичен Link за тем исключением, что позволяет использовать состояние ссылки. В частности, с помощью атрибутов className и style можно установить стиль активной ссылки. Так, изменим веб-станицу следующим образом:

    Маршруты в React a < margin:5px;>.active          

Для стилизации активной ссылки в стилях страницы определен класс active . Атрибут className устанавливает этот класс:

className=<(< isActive >) =>(isActive ? " active" : "")>

В качестве значения атрибут получает функцию, которая в качестве параметра получает объект со свойством isActive . Если данная ссылка представляет текущий путь, то это свойство равно true . Соответственно мы можем проверить значение этого свойства и в зависимости от результатов проверки установить или убрать класс active для ссылки: isActive ? » active» : «»

Обратимся к приложению, и теперь активная ссылка будет стилизована:

Стилизация ссылок в React

Естественно в данном случае, чтобы не повторяться, мы можем вынести установки класса во внешнюю функцию:

const setActive = (< isActive >) =>(isActive ? " active" : ""); function Nav() < return ; >

Также вместо атрибута className для стилизации активной ссылки можно использовать атрибут style , который работает аналогичным образом:

) =>()>>Главная 

В данном случае опять же атрибут использует функцию, которая в качестве параметра принимает объект со свойством isActive , если оно равно true , то устанавливаем стиль color:green , иначе ссылка получает синий цвет.

React NavLink vs. Link: Comparing Use Cases and Examples

React is a popular JavaScript library for building user interfaces, and when it comes to routing in React applications, developers often have to choose between two components: NavLink and Link. Both components are provided by the react-router-dom library and serve similar purposes but with some key differences. In this article, we will explore the use cases for both NavLink and Link and provide code examples to illustrate their usage.

Understanding NavLink: NavLink is a specialized version of Link that adds styling and functionality for handling active links. It is commonly used in navigation menus where we want to highlight the currently active link. NavLink applies an “active” class to the rendered element when the current URL matches the link’s “to” prop.

Use cases for NavLink:

  1. Navigation menus: NavLink is perfect for building navigation menus where we want to visually highlight the active link, giving users clear feedback about their current location within the application.
  2. Sidebar or tabbed interfaces: When using a sidebar or tabbed interface, NavLink can be used to highlight the selected tab or menu item.

Example usage of NavLink:

import < NavLink >from 'react-router-dom';

const NavigationMenu = () => return (

);
>;

export default NavigationMenu;

In the above example, the NavLink components are used to define the navigation links. The “to” prop specifies the target URL for each link, while the “activeClassName” prop sets the class name to be applied when the link is active.

Understanding Link: Link is a basic component used for declarative navigation in React applications. It renders an anchor tag () with the appropriate href attribute, allowing users to navigate to different routes without triggering a full page reload.

Use cases for Link:

  1. Basic navigation: Link is suitable for creating links within the…

Разница между и в React Router

В React Router оба компонента и используются для навигации, но у них есть различия в функциональности и областях применения.

import < Link >from 'react-router-dom'; // . About
  • является расширением и предоставляет дополнительные возможности, особенно в отношении стилизации.
  • Также отрисовывает элемент якоря ( ).
  • Добавляет специальный класс к отрисованному элементу, когда он соответствует текущему маршруту, что позволяет применять различные стили к активной ссылке.
  • Принимает свойство под названием activeClassName для указания имени класса, применяемого к активной ссылке.
import < NavLink >from 'react-router-dom'; // . About

В этом примере, когда маршрут «/about» активен, отрисованный элемент якоря будет иметь класс «active», что позволяет стилизовать его по-другому.

В итоге используйте для базовой навигации и , если вам нужны дополнительные возможности для стилизации активных ссылок. Сделайте выбор в зависимости от ваших конкретных требований и потребностей в стилизации в вашем приложении.

React Router DOM: The Differences Between NavLink, Link, and
Thought leadership from the most innovative tech companies, all in one place.

How to use NavLink, Link, and — explained with examples.

Link

If the «to» attribute is an object, it will render an anchor tag with an href equal to the pathname of the object. If the object version of the «to» attribute is used, you can pass four different properties: pathname (the path link), search (query params), hash (to put in URL), and state (persisting state).

NavLink

NavLink is a component provided by react-router-dom that allows users to navigate throughout the React application. NavLink is similar to Link, but it has the ability to add additional styling attributes to the element. For example, you can use NavLink to style the active link differently than the other links. NavLink utilizes the «activeClassName» attribute. This is the class that will be applied to the element when it is active.

The NavLink component has an activeClassName of ‘active’, which will enable when the user is on the about page. You can style the activeClassName in a CSS file. For example, if we wanted the NavLink to be green when it is active, we could write the following CSS:

Anchor Tag ()

An anchor tag is an HTML element that is used to create a link to another page. The anchor tag has an href attribute, which specifies the URL of the page that the link goes to. The anchor tag is different than Link and NavLink because it does not utilize React Router. It is used for linking to external pages or for creating links that do not go to a specific route in the React application.

Which to Use When?

Now that we have gone over the differences of each link, when should you use which one? If you want to create a link within your React application, that does not need styling when it is active, use the Link component. If you want to create a link within your React application, that does need styling when it is active, use the NavLink component. Lastly, if you want to create a link to an external page or a non-route within your React application, use the anchor tag.

Conclusion

I hope this article taught you something. Good luck with your projects!

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

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