Contenido del Curso
Expert React
Expert React
Navigation
Step 5: Create Navigation
After setting up the basic routing and implementing lazy loading and fallbacks, we now need to create navigation links to enable users to navigate through the pages of our app.
To achieve this, React Router provides the Link
and NavLink
components, which serve as analogs to the HTML a
tag. These components allow us to update the URL in the browser address bar without reloading the page.
Here is an example of using the Link
component:
- Line 1: It imports the
Link
component from thereact-router-dom
library. - Line 3: The
<Link>
element represents a link. It allows users to navigate a specific route or path in the application.to="path_value"
: Theto
prop specifies the target route or path that the link should navigate to. We replacepath_value
with the actual path we want the link to point to.Any text
: The text or content will be displayed as the link. We can replaceAny text
with the desired text or JSX content.
Note
The
Link
andNavLink
components are similar, but theNavLink
component provides additional styling options if the current URL matches theto
prop value.
We can customize the to
prop and the link's content per the application's requirements.
Example: Let's create a separate component called Bar
to handle the navigation for the entire app.
Code explanation: This code defines a functional component called Bar
that represents a navigation bar. It renders a <nav>
element containing an unordered list <ul>
with three list items <li>
. Each list item includes a Link
component from the react-router-dom
library.
- Line 6: The first
Link
component represents a link to the "Home" page. - Line 9: The second
Link
component represents a link to the "About" page. - Line 12: The third
Link
component represents a link to the "Contacts" page.
These Link
components enable navigation within the application by updating the URL in the browser address bar without reloading the page. When a user clicks on a link, the corresponding route or path is activated, and the associated component will be rendered.
After creating the Bar
component, we can incorporate it into the App
component, where we build the complete app. Including the navigation component before the Suspense
component is essential to ensure consistent access to navigation throughout the app.
Complete code
Please take a moment to click the links and observe the view's re-rendering. Additionally, inspect the App
and Bar
components closely as they encompass the complete React Router logic for this app.
¡Gracias por tus comentarios!