Какая разница между link navlink в react router
В прошлой теме для обращения к ресурсам внутри приложения были использованы маршруты. Теперь добавим к этому приложению навигацию с помощью ссылок. Для этого изменим файл index.html следующим образом:
Маршруты в React
Для создания ссылки применяется объект Link, который определен в модуле react-router-dom:
const Link = ReactRouterDOM.Link;
Для определения блока навигации здесь добавлен компонент Nav:
function Nav() < return ; >
Для каждой ссылки с помощью атрибута to определяет путь перехода.
Затем компонент Nav помещается в объект Router. И после запуска мы увидим блок ссылок, по которым сможем переходить к ресурсам приложения:
Аналогичный пример с использованием компонентов-классов:
Маршруты в 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» : «»
Обратимся к приложению, и теперь активная ссылка будет стилизована:
Естественно в данном случае, чтобы не повторяться, мы можем вынести установки класса во внешнюю функцию:
const setActive = (< isActive >) =>(isActive ? " active" : ""); function Nav() < return ; >
Также вместо атрибута className для стилизации активной ссылки можно использовать атрибут style , который работает аналогичным образом:
) =>()>>Главная
В данном случае опять же атрибут использует функцию, которая в качестве параметра принимает объект со свойством isActive , если оно равно true , то устанавливаем стиль color:green , иначе ссылка получает синий цвет.
React Router v4 vs benefits
Besides the ability to set an «activeClassName» and «activeStyle» on NavLink, is there any reason to use NavLink over Link when creating links to other routes on non-navigational elements (ie. not main nav in header or footer) on your site that don’t need an active state/class?
5,660 2 2 gold badges 38 38 silver badges 45 45 bronze badges
asked Nov 16, 2017 at 19:56
1,541 2 2 gold badges 11 11 silver badges 12 12 bronze badges
I can’t comment directly to TOUMI (because I don’t have 50rep), so I’ll add it here. NavLink keeps the proper focus on the page for accessibility. When using link, initial focus is lost on page load and you will also notice that tabbing through dropdowns also breaks when using Link . NavLink fixes this.
Jul 11, 2019 at 20:08
7 Answers 7
A special version of the that will add styling attributes to the rendered element when it matches the current URL.
Thus, the answer is NO. There are no other reasons except the mentioned one.
3,141 2 2 gold badges 28 28 silver badges 33 33 bronze badges
answered Nov 16, 2017 at 20:06
Abdennour TOUMI Abdennour TOUMI
88.1k 38 38 gold badges 251 251 silver badges 256 256 bronze badges
When you need to use style or class attributes on active , then you can use
Let see the example:
Link
Home
NavLink
Home
answered Mar 19, 2018 at 18:17
Sultan Aslam Sultan Aslam
5,660 2 2 gold badges 38 38 silver badges 45 45 bronze badges
Link Component
It is used to create links which allow to navigate on different URLs and When we click on any of that particular Link, it should load that page which is associated with that path without reloading the page. Example:
NavLink Component:
If, we want to add some styles to the Link. So that when we click on any particular link, it can be easily identified which Link is active. For this react router provides NavLink instead of Link. Now replace Link from Navlink and add properties activeStyle. The activeStyle properties mean when we click on the Link, it should be highlighted with different style so that we can differentiate which link is currently active. Example:
Implementing React Routes (Part -2) Link Vs NavLink
Hello guys
In our previous tutorial, we learned how to add simple routes to our react app.
Today will be a short tutor on when to use NavLink and Link tags in React and we shall concentrate on the Nav component created in the last tutorial. Link
Overview
Before getting started, it is important to know that react uses the JSX(JavaScript XML) syntax which allows you to write JavaScript in HTML in a nice and easy way.
For more details about JSX, Click here
What is NavLink and Link in React?
The react-router-dom parckage we installed in the previous tutorial gives your access to using either the NavLink or the Link which we can use as tags, This is actually is the representation of the ‘href’ attribute of the anchor tag or the ‘window.location.href’ object.
What is the difference between NavLink and Link?
Well actually, the main difference between these two’s is a class attribute. When we use the NavLink as a tag, it automatically inherit an active class when clicked. On the other hand, the Link tag does now have an active class when clicked.
When should I use the NavLink?
Just as the name implies ‘NavLink’, we use it mostly on navigation bars. This is because the active class permits us to define our custom styling in the App.css stylesheet. As such, we can use it to style our active buttons which in notify the use on which page he/she is currently on.
When should I use the Link?
The Link tag can be used where we want to do just some routing with no special effect. For instance; we can use the Link tag for scroll-to-top button, add to card buttons, submit button and more.
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:
- 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.
- 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:
- Basic navigation: Link is suitable for creating links within the application, such as navigation between different pages or sections.
- Action buttons: Link can also be used to create buttons that trigger navigation when clicked.
Example usage of Link:
import < Link >from 'react-router-dom';
const HomePage = () => return (
Welcome to my website!
Learn more
);
>;
export default HomePage;
In the above example, the Link component is used to create a “Learn more” button that navigates the user to the “/about” route when clicked. It provides a seamless navigation experience without reloading the entire page.
Choosing between NavLink and Link: When deciding between NavLink and Link, consider the specific requirements of your application. If you need to highlight the active link in a navigation menu or tabbed interface, NavLink is the recommended choice. On the other hand, if you simply need to create links for navigation or action buttons, Link provides a straightforward solution.
NavLink and Link are essential components in React applications for managing navigation and creating links. By understanding their use cases and differences, you can make informed decisions on when to use NavLink for active link highlighting and when to use Link for basic navigation or action buttons. With the code examples provided, you can start integrating these components into your own projects more effectively, enhancing the user experience of your React applications.