Styling in Next.js with conditions

I am attempting to create a scenario where a link becomes active if the pathname matches its href value.

function Component() {
 const pathname = usePathname();
  return (
      <div className="links">
        <Link href="/">Home</Link>
        <Link href="/store" className={`${pathname === this.href && "active"}`} >Store</Link>
        <Link href="/actors">Actors</Link>
      </div>
 )}

I have attempted the above code but unfortunately, it is not yielding the desired result. Is there an alternative method I could try?

Answer №1

Using this in functional components is not allowed, as it is only accessible in class components. If you want to achieve that same functionality, you will need to manually write the code like this:

<Link href="/store" className={`${pathname === "/store" ? "active" : ""}`} >Store</Link>

Additionally, avoid using && in className, as it may add false to your className if the condition fails. Instead, use a ternary operator with an empty string in the false condition.

Answer №2

In addition to the insights shared by Rao Asim, one way to prevent repetition is by organizing them into an array and then using the .map method to iterate over the array.

function Component() {
 const pathname = usePathname();
  return (
      <div className="links">
        {[
          { label: "Home", href: "/" },
          { label: "Store", href: "/store" },
          { label: "Actors", href: "/actors" },
        ].map(({label, href}) => (
          <Link 
            key={label} 
            href={href}
            className={pathname === href ? "active" : ""}
           >{label}</Link>
        ))}
      </div>
 )}

To enhance readability, you can extract the array declaration from the JSX:

function Component() {
  const pathname = usePathname();

  const navElements = [
    { label: "Home", href: "/" },
    { label: "Store", href: "/store" },
    { label: "Actors", href: "/actors" },
  ]

  return (
      <div className="links">
        {navElements.map(({label, href}) => (
          <Link 
            key={label} 
            href={href}
            className={pathname === href ? "active" : ""}
           >{label}</Link>
        ))}
      </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

If the div is visible in the viewport, then automatically scroll to the top

Struggling to locate online resources for this particular technique. In my JSFiddle, users can navigate through fullscreen divs using 'next' or 'prev', as well as scrolling to access the next or previous divs. The issue arises when us ...

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...

Troubleshooting EasyTabs: Localhost Issue with Ajax Tab Configurations

I've implemented EasyTabs for organizing my tabs on a webpage. I decided to use ajax-tabs functionality in order to fetch content from other pages when users click on the navigation menu buttons. However, I've encountered an issue where the conte ...

Dynamic routing in Next.js with express leads to the refreshing of the page

I am facing an issue with my Next.js blog application that I built using an express custom browser. Whenever I click on a Link to route to '/blog/article-1', the page refreshes upon arrival at the destination. How can I prevent this from happenin ...

Generating a Popup Alert with a DIV

Looking at this instance: HTML / CSS Popup div on text click I am curious about how to have this display on the main page upon initial visit to the website. I prefer it to load automatically without requiring a button click, and once the content is read, ...

Strange formatting in the internet explorer browser (IE)

I have encountered an issue with CSS animation elements on the home page. The animations appear correctly in Google Chrome, but there is a strange indentation problem when viewed in IE. I have tried several solutions without success. Although I am not a w ...

Ways to resolve the issue of iOS Safari showcasing 'a' tag styling differently compared to other browsers

Here's a simple question for you. Take a look at the images below for reference. Check out the iOS Safari browser on my phone https://i.sstatic.net/o9jOe.jpg and compare it to my desktop browser, both screenshots were taken live from the server. ...

disappearance of background image at bootstrap breakpoint

Hey there, I'm diving into a new journey in web design and I've encountered my first newbie issue. I'm attempting to place an image and text side by side on my web layout, but as soon as the breakpoint hits below 560px, the image disappears ...

The footer is being covered by the section, despite my attempts to address the issue with

I have noticed a section overlapping issue and I am struggling to figure out the cause. I have attempted using margins and padding to adjust the footer with my .div-wrap, but so far it has not been effective. After searching around, I am still uncertain ...

Using JavaScript to open links in a new tab with the target

document.getElementById("mahacareer").onclick = function () { window.open("http://www.mahacareermitra.in", '_blank'); }; <a href="" id="mahacareer">Access the portal</a> Hi there, I am looking to have the link above open in a new tab ...

Adjusting font size in dynamic containers relatively

Imagine we have a slider named .outer, which adjusts its height based on the width of the viewport. Inside this slider, there is an example slide called .inner that contains some text. However, when we shrink the window width, the content in slide .inner s ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

Footer that sticks to the bottom of the page across various pages

Having trouble printing a 2-page document on Chrome. The first page has fixed content while the second page has dynamic content in an extended table. The problem I'm facing is keeping the footer at the bottom of the second page. The CSS code below wo ...

Reimagining scrolling through content with a stylish unordered list (a sleek alternative to a select box

After having our company website redesigned by a professional designer, our site now looks much more visually appealing. However, I have encountered difficulties when trying to implement their design using HTML and CSS. One particular challenge is the heav ...

Tips on expanding the space between words in a scrolling "marquee" text

Looking for some assistance with my jQuery project involving a horizontal scrolling "marquee" text. I am currently trying to adjust the size of the gap between the phrases in the marquee. Here is an example with the phrase "HEY THERE". jQuery(document ...

"Implementing a form loading state in NextJs Server Action: A Step-by-Step

I've been struggling to figure out how to capture the loading state in a NextJs Server Action. While I know there's a solution using client components and routes API, my situation calls for using a React server action. NextJs 13/14 doesn't a ...

Use CSS to apply hover effects to multiple sections of text at the same time

Is there a way in CSS to apply the hover state to one part of HTML text when another part is hovered over, both sharing the same class? I have a block of text in HTML that is broken down into individual words, each word linked to a specific CSS class. It ...

Not all Angular Material2 styles are being fully applied

One issue I am encountering is that styles for components such as <mat-chip> or <button mat-raised-button> (the only ones I have found) are not working properly and appear gray by default. However, styles do apply correctly to the <mat-card& ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

What is the best way to ensure that a navbar dropdown appears above all other elements on

I'm having trouble creating a navbar dropdown with material design. The dropdown is working fine, but the issue I'm facing is that other elements are floating above it. https://i.stack.imgur.com/aJ0BH.png What I want is for the dropdown to floa ...