Update the component with the current route and state synchronization with react router dom

Is there a method to synchronize the active route in the browser with the component state?

When I click on "Route 2" in the navigation bar, it gets highlighted as the active route and the browser URL shows "/route2". However, upon refreshing the page, "Route 1" is highlighted even though the browser URL still displays "/route2". Is there a way to keep these two in sync?

To replicate this project, start a new app using vite with react-ts, and then include the following files:

App.tsx

[Code snippet for App.tsx]

[More file setups with code snippets...]

package.json

[Code snippet for package.json]

tailwind.config.js

[Code snippet for tailwind.config.js]

postcss.config.js

[Code snippet for postcss.config.js]

main.tsx

[Code snippet for main.tsx]

index.css

[Code snippet for index.css]

Finally, delete the contents of App.css.

Answer №1

Don't rely on manually calculating the active route/link when you can use the NavLink component in React Router. The NavLink component automatically handles this functionality for you. You can utilize the children prop of the NavLink to pass a render function prop value that includes an isActive prop which can be used to conditionally apply UI logic within the child components.

<NavLink to="/tasks">
  {({ isActive, isPending, isTransitioning }) => (
    <span className={isActive ? "active" : ""}>Tasks</span>
  )}
</NavLink>

For example:

...
import {
  Routes,
  Route,
  Navigate,
  NavLink,
  Outlet
} from "react-router-dom";
...

const Navbar = () => {
  return (
    <div className="flex justify-between items-center sticky top-0 border-b bg-background px-4 h-12 z-10">
      <h1>App Name</h1>
      <div className="flex gap-4 h-8 items-center">
        <NavLink to="/route1">
          {({ isActive }) => (
            <h2
              className={cn(
                "hover:underline hover:text-blue-500",
                isActive ? "text-blue-500" : null
              )}
            >
              Route 1
            </h2>
          )}
        </NavLink>
        <NavLink to="route2">
          {({ isActive }) => (
            <h2
              className={cn(
                "hover:underline hover:text-blue-500",
                isActive ? "text-blue-500" : null
              )}
            >
              Route 2
            </h2>
          )}
        </NavLink>
      </div>
    </div>
  );
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring D3 Geo World Map Zooming with ReactJS

I have a web app built with ReactJS that includes a world map created using D3 in one of the components. The map currently allows users to zoom in on a specific country when clicked, but I want to enable them to zoom in with a custom amount by simply scrol ...

Most effective methods for validating API data

Currently, I am working on developing an api using nestjs. However, I am facing some confusion when it comes to data validation due to the plethora of options available. For instance, should I validate data at the route level using schema validation (like ...

What is the best way to ensure a division's height matches that of the window using CSS?

Is it possible to create a division that covers the total width and height of the screen using just CSS without relying on JavaScript or jQuery? <div id="all"></div> I have tried setting the width and height of the element to 100%, but I am s ...

Utilizing React-Engine and Express to Transfer Server-Side Variables to Client-Side

I'm fairly new to working with React and React-Engine. I have a server-side configuration that contains certain values that need to be passed to the client-side. However, I rely on NODE_ENV to determine which specific configuration to use. var config ...

Increase the font size of a div using CSS to make it appear larger

Utilizing a WYSIWYG-editor, I am creating content that I want to display with double font-size, without directly altering the HTML code. Here is an example of the HTML structure: <div id="contents"> <p style="text-align:center"> <spa ...

Is it worth diving into Vue.js, Angular, or React while utilizing Laravel currently?

After spending 2 months immersing myself in Laravel, I am considering expanding my skills by learning a JavaScript framework. While I have discovered that Laravel comes bundled with Vue.js, there are also options like Angular and React.js which are more po ...

Optimizing your data layer in Angular2: A Guide to Best Practices

As a newcomer to Angular2, I am diving into hands-on learning. My current project involves building multiple views with parent components, child components, and database services. After successfully creating one view, I am now gearing up to implement other ...

Tips for positioning a div relative to another div while controlling its z-index

Hey there, take a look at the image below https://i.sstatic.net/zYiaY.png The issue I'm facing is quite common - I have div 1 and div 2 visible in a loop, but divs 3 are hidden. When div 2 is clicked on, everything is great so far. However, what I wa ...

Step-by-step guide: Creating a captivating triangular shape on the current tab

I am trying to implement a dynamic tab using Bootstrap where clicking on a tab will display a thicker black underline, like in this image: https://i.stack.imgur.com/h48GB.png To achieve the black line effect, I have added the following code: .nav-tabs.n ...

Error message: The content of the webpage does not align with the server-rendered HTML

I'm currently working on setting up next.js with Azure AD B2C using the MSAL (React) library. The MSAL library provides a convenient component called <MsalAuthenticationTemplate /> to handle authentication. To demonstrate this, I created a basi ...

Tips for patiently anticipating the completed response within an interceptor

Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly: ngOnInit() { this.spinnerService.show(); this. ...

What is the process for setting up a vertical carousel in Bootstrap 5 with a stationary previous image?

Looking for assistance with my vertical carousel project. Is there a way to create a vertical carousel in bootstrap 5 with the previous image fixed? I found a slider on this website: zara.com/jp/en/ I want to maintain the previous image in a fixed posit ...

Copy the style of a chosen element and apply it to another element

One of the challenges I'm facing involves a dynamic span element that changes based on color selection: <span class="color checked" style="background-color: #ff0000">Red</span> In addition, I have an image element wit ...

Is there a print button in Drupal similar to a print link?

Is there a way in Drupal to create a button using an API function similar to the print link function? <?php print l(t('Announcement'), 'node/30'); ?> l turns text into a link. I'm looking for a way to create buttons in Drup ...

Precommit hook failing to activate despite errors occurring

"scripts": { "precommit": "pretty-quick --staged & npm run lint & npm run test", "lint": "eslint 'src/**/*.{js,jsx}' --quiet --fix", "test": "cross-env CI=true react-scripts test --env=jsdom --coverage" } https://i.sstatic.net/M ...

Setting up the react-ultimate-pagination component

I've been experimenting with the react-ultimate-pagination package available at: https://github.com/ultimate-pagination/react-ultimate-pagination My goal is to configure it in a way similar to their basic demo showcased here: https://codepen.io/dmytr ...

What is the method for implementing 'gtag_report_conversion' to track conversions in Google AdWords within a React.js environment?

I am feeling lost on how to utilize this information. The instructions suggest calling gtag_report_conversion when the specific action I wish to track occurs. My goal is to monitor signups on my site, which would be confirmed in my reducers actions file po ...

Using setTimeout within a for loop to dispatch notifications

I'm facing an issue with sending notifications based on certain parameters. I attempted to use a combination of for loop and setTimeout in my code, but all the notifications are sent simultaneously instead of at timed intervals. The relevant snippet l ...

Is it possible to change the CSS of a parent element using a child element?

My current challenge involves altering the background-color of a parent <td> element, without being able to directly modify the HTML structure. The software system utilized at my workplace strictly relies on SQL queries for data manipulation and gene ...

Every time I try to access a Heroku deployed link, I encounter a 500 error (Internal Server Error)

Whenever I use http://localhost:5000/login everything works perfectly fine. However, when I utilize the live link , an error occurs stating POST 500 (Internal Server Error) The code snippet below using the live Heroku link: This particular code is not fu ...