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

Overflow scroll block containing a table within a div element

I am working on displaying a loop of records fetched from the database. I want to place these records inside a div block with overflow so that users can scroll through a long list easily. However, when I try to implement the below code, the appearance of t ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

The vanishing HTML Div with a fixed height

After implementing a navigation bar inside my header container, I noticed that the main_image div with a blue background color disappeared. Despite setting a height for it, the div was nowhere to be seen. Additionally, the welcome_text div seemed to lose i ...

Encountered a bus error resulting in a core dump while initializing a NextJs project

After completing the setup of my NextJs project, I attempted to start it by running npm run dev. However, instead of launching the project, the terminal shows an unexpected output that appears to be causing an issue. I am unsure of what is causing this p ...

Retrieving information from the API and displaying it is a time-consuming process

navigation links import { v4 as uuid } from "uuid"; import Link from "next/link"; import { getAllCategories } from "src/utils/api"; export default async function NavLinks() { const {data: categories} = await getAllCategorie ...

Creating a visual that when clicked, reveals an enlarged version at a different location

Is there a way to make an image appear in a different location on the page when it's hovered over? I've searched online but couldn't find a solution using just HTML and CSS. Does anyone know how to achieve this effect? Image not hovered: ht ...

The primary tab's background color in a Shiny app

I had this question deleted previously while I was in the process of refining it. Is there a way to customize the background color of the active tab in a Shiny app? library(shiny) ui <- fluidPage( tags$head( tags$style(HTML(css)) ), tabsetP ...

Ensure that the divs are properly aligned with the paragraphs

I received assistance previously, and I am seeking additional help in maintaining the position or adjusting the size of elements to fit different window viewport sizes such as tablets, mobile devices, or varying monitor sizes while keeping the appearance c ...

What is the method for adjusting the subheader color on a Material UI card component?

How can I change the subheader text color to white in a Material UI Card with a dark background? Here is my code: const useStyles = makeStyles(theme => ({ menuColor: { backgroundColor: theme.palette.primary.main, color: '#ffffff', ...

The transparent DIV/waiting message may not be displayed in IE10

Here is a DIV container that serves as a transparent background with a loading message. This is the HTML code for the DIV container: <div id="generatingexcel" style="display:none; position: fixed; width: 100%;height: 100%; z-index: 999; top: 0; left: ...

Issues encountered with initializing builder.io using npm

I have been working on developing a web application with Builder.io and everything was running smoothly until I decided to try installing 'pnpm'. When I attempted to run the command 'npm init @builder.io', it failed with an error messag ...

Shifting an HTML anchor to account for a stationary header - Safari compatibility with alternative CSS styling

I made adjustments to my HTML anchors by adding an offset in the CSS to accommodate for a fixed header in my theme: margin-top: -175px; padding-top: 175px; } /* Adjustments for screen sizes of 760px and smaller */ @media (max-width:760px){ #r ...

Dealing with CSS specificity issues when incorporating material-ui for React into a WordPress plugin

Struggling to integrate material-ui for react in a wordpress plugin due to conflict with wordpress's styling in forms.css file. Looking for a solution that doesn't require complete restyling of material-ui components to override the default style ...

Guide to deploying a NextJs SSR React application on Microsoft Azure

Recently, I attempted to deploy a Server-side rendered react app that I developed using NextJS on Azure. Despite successfully setting up the Azure pipeline and release process, the app failed to load when I accessed the Azure website URL. One of the challe ...

jQuery navigation is experiencing issues due to conflicting buttons

I am currently developing a web application that features two buttons in the header: Share and Options. When a button is clicked, its related content expands and collapses when clicked again. The issue arises when the user clicks on the share button and th ...

Why do certain full screen websites not align with my screen width properly?

When I use my 1920px wide screen and inspect the HTML tag with Chrome DevTools on websites like Firebase or Facebook Messenger, I notice a difference: Despite my screen width being 1920px, these websites appear fullscreen with an HTML tag width of 1440px. ...

What specific features does CSS3 offer in terms of background-size properties?

Let's delve into my knowledge: $, like in font-size: 14$; em, as in margin: 2em; What other units are out there? ...

Bringing together embedded chat and stream seamlessly with CSS styling

I'm in the process of integrating a chat feature with my Twitch stream on a Xenforo forum page. I aim for the stream to be displayed in 16:9 aspect ratio to ensure high definition quality, and I want it to adapt to the user's screen resolution. B ...

Pictures may become distorted when their width is smaller than the container

In my current project, I am facing an issue with maintaining the aspect ratios of images of different sizes. Most of them are looking good except for those whose width is smaller than the container's width of 285px. Even though some blurriness is acce ...

Steps for deploying and setting up a next.js application on a rented server that has apache2 already installed

I am new to deploying applications and have been looking for information on how to deploy a next.js app on Vercel or other servers that support it. However, I have my own server that I rent, and I have managed to deploy and run the app locally on the ser ...