Obtain the current route path while statically rendering页面

I'm using Next.js (v14/app router) to create a statically exported website. However, I'm facing an issue with implementing a tab bar in one of my layouts for easy page navigation.

Here is a simple example:

<div className="tabs">
    <Link href={`/post/${p.slug}`}>All wins</Link>

    <Link href={`/post/${p.slug}/top`}>Top wins</Link>

    <Link href={`/post/${p.slug}/stats`}>Statistics</Link>
</div>

The problem arises when setting the active classname based on the current route. Is there a way to access the current route of the page to dynamically apply the active class like

className={currentRoute === '/post/${p.slug}/stats' ? 'active' : ''}
?

I am aware of the usePathname method, but using it on the client-side seems inefficient. Is there a way to achieve this during page rendering?

Answer №1

Indeed, I believe utilizing a client component in this scenario is a perfect fit. It offers a seamless way to monitor the active segment with convenience. Consider the code snippet below as an illustration:

"use client";

export default function CustomTabComponent({ content }: Properties): JSX.Element {
  const path = usePath();

  const paths = useMemo(() => {
    const contentPaths = [
      `/content/${content.identifier}`,
      `/content/${content.identifier}/overview`,
      `/content/${content.identifier}/details`,
    ];

    return contentPaths.map((p) => ({
      link: p,
      isActive: path === p,
    }));
  }, [path, content.identifier]);

  return (
    <ul className="tabs">
      {paths.map((p) => (
        <li key={p.link}>
          <Link href={p.link} className={p.isActive ? "active" : ""}>
            Select Option
          </Link>
        </li>
      ))}
    </ul>
  );
}

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

The power of Karma, AngularJS, Bootstrap, and the window variable working

As I work on testing my application, I am facing an issue with loading files using Karma into PhantomJS. The problem arises when one of the files triggers a page reload due to window variables. The files are being included in this manner: files: [ &a ...

Dominate with asyncCommand and Ajax in MVC ActionResults

I am currently diving into front-end development and working on a project that involves fixing bugs. Right now, I am utilizing Knockout/MVC ActionResults. One of my tasks is to modify a form so that it cannot be submitted with a double click. I initially ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...

Can users' data be securely stored in the session/history using ReactJS?

I recently inherited a React application from a previous developer, and while I'm still getting the hang of how React works, I am surprised to see that user data is being stored in the session history. This raises some concerns for me: const { ...

How to efficiently remove duplicate items from multiple select dropdowns in Angular using ng-repeat?

Need help with dynamically assigning objects to select boxes in AngularJS. I have a scenario where I add multiple select boxes to a form, but each box should only display items that haven't been selected in other boxes. How can I achieve this functio ...

Only validate the nested object if the parent object is already present

In my scenario, I have a request body structured as follows: { "folder": { "value": "testFolder", "operator": "=" }, "name": { "value": "5456", "operator": "contains" } } While the presence of the request body is optional, I want to ensure that b ...

What is the best way to ensure that a task is performed only once the DOM has finished loading following an AJAX request

<div id="mydiv"> ... <a id="my-ajax-link"> ... </a> ... ... <select id="my-selectmenu"> ... </select> ... </div> Upon clicking the 'my-ajax-link' link, it triggers an AJ ...

Guide to manipulating DOM elements with Angular.js: inserting or deleting elements using createElement

Within my Angular directive, I am dynamically generating an external script from the DOM for a specific object within a list. This script includes both a 'script' tag and div content. While I am able to successfully add the script, I am encounter ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

ToggleClass is not being applied to every single div

I am currently designing a pricing table with hover effects. You can view the progress here: Upon hovering on a pricing table, all the divs are toggling classes which is not the desired behavior. I want each element to have its own separate interaction. ...

Is there a way to display the entire stack trace in Mocha when testing Promises and an error occurs?

Imagine I have a small specification like this: describe("feature", () => { it("does something", () => { return myPromiseBasedFn().then(result => { expect(result).to.eql(1); }); }); }); At the moment, when the promise is reject ...

What steps do I need to take in order to implement a Next.js project using the http protocol in a production

Currently, I am in the process of creating an intranet webpage that will be hosted on a private network using Next.js. However, when the production-level Next.js web app is built and running, it forces the loading of files (CSS, JS, images) via the HTTPS ...

I am having trouble resolving 'otp-input-react' in my project directory at D:projectappsrc

I have been troubleshooting this issue but haven't been able to find a solution yet. I even tried uninstalling and reinstalling the package, but it still isn't working as expected. Here are some images for better clarity: https://i.stack.imgur.c ...

Achieving the functionality of making only one list item in the navbar bolded upon being clicked using React and Typescript logic

Currently, in my navigation bar, I am attempting to make only the active or clicked list item appear bold when clicked. At the moment, I can successfully achieve this effect; however, when I click on other list items, they also become bolded, while the ori ...

How can I access specific values from a table generated with a PHP array using jQuery?

Currently, I am working on a page where users can upload documents. Once uploaded, these docs are stored in a folder and their location is updated in a table for reference. Now, when I navigate to an edit page, I use PHP to query the database and display t ...

Different option for animated side slider based on location

Whenever I click on this div, it slides out smoothly. Check out these images to get a visual of what I am aiming for: This is how the Div looks when collapsed by default https://i.stack.imgur.com/zJIsA.png Once slid out, the Div looks like this (highlig ...

Enhancing UI design with Vue.js

I'm attempting to customize elements using data from a JSON file in Vue.js: <div v-for="(item, index) in json._items" class="help-inner-callout" v-html="item.text" style="top:item.top; left: item.left;">&l ...

Find elements that are not contained within an element with a specific class

Imagine having this HTML snippet: <div class="test"> <div class="class1"> <input type="text" data-required="true"/> </div> <input type="text" data-required="true"/> </div> I'm looking to select ...

Having trouble creating a polygon from JSON in ESRI ArcGIS Javascript framework?

Can anyone assist with understanding the issue of trying to draw a polygon using the ESRI ArcGIS Javascript API? The image, JSON string, and code snippets provided below outline the code, console output, and expected behavior. Any help would be greatly app ...

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...