What is the difference between class at DOM and className at component?

When passing the className props to the child component, sometimes the className for the active link is not correctly reflected in the DOM element during production:

  • The child component (Link) receives the className prop for the active link from the parent.

  • The child component (Link) in the DOM does not apply the class if the link is active.

This is how my code looks:

  • Navbar
// Navbar.tsx
import classnames from 'classnames';
import { useRouter } from 'next/router';
...

const Navbar = () => {
  const router = useRouter();

  const navigations = [
    {
      href: '/',
      label: 'Home'
    },
    {
      href: '/profile',
      label: 'Profile'
    }
  ];

  return (
    ...
          {navigations.map((nav) => (
            <NavLink key={nav.label} href={nav.href} isActive={router.asPath === nav.href}>
              {nav.label}
            </NavLink>
          ))}
    ...
  );
};

export default Navbar;
  • Parent component
// NavLink.tsx

import classnames from 'classnames';

import Link from '@/components/elements/Link';
import styles from '@/components/parts/Navbar/styles.module.scss';

import type { NavLinkProps } from './types';

const NavLink = ({ children, href, isActive }: NavLinkProps) => (
  <Link
    href={href}
    className={classnames(styles.navbar__link, {
      [styles.navbar__link_active]: isActive
    })}
  >
    {children}
  </Link>
);

export default NavLink;
  • Child component
// Link.tsx

import dynamic from 'next/dynamic';

import type { LinkProps } from './types';

const NextLink = dynamic(() => import('next/link'));

const Link = ({ children, href, target, isExternal, className, label, role }: LinkProps) => {
  if (isExternal) {
    return (
      <a
        href={href}
        target={target ?? '_blank'}
        rel="noopener noreferrer"
        className={className}
        aria-label={label}
        role={role}
      >
        {children}
      </a>
    );
  }

  return (
    <NextLink href={href}>
      <a target={target ?? '_self'} className={className} aria-label={label} role={role}>
        {children}
      </a>
    </NextLink>
  );
};

export default Link;

Answer №1

Consider utilizing template literals:

<NavLink className={`${classNames(styles.header__link, {
    [styles.header__link_active]: isActive
}}`}>

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

What could be causing the last LI to drop onto a new line when floating UL to the right?

I'm currently working on creating a horizontal navigation that needs to align to the right side of the page. However, when I float the navigation to the right and then float all the list items to the left, the last item in the list breaks onto a new l ...

Utilizing the Laravel back-end API within the getServerSideProps() function in Next.js

Currently, my setup involves using next js for the front-end and laravel for the back-end. I am attempting to make an API call to the back-end (laravel) from the getServerSideProps() method as demonstrated below: export async function getServerSideProps(co ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

Struggling to retrieve object values through useContext? Consider implementing useReducer in conjunction with useContext for more efficient state management

I'm facing an issue while trying to access my dispatch functions and states from the useContext. Strangely, when I attempt to destructure the context object in order to access them directly, I receive an error message stating that it does not exist (E ...

Incorporate HTML and JavaScript to dynamically show a button when a specified condition evaluates as true and hide the button if the

I need help with a scenario where I want to show a button only when a specific variable reaches a certain value. For instance, if the variable equals 5, the button should be displayed; otherwise, it should be hidden. Here are the two buttons included withi ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Why does the warning in `middleware.ts` still linger even after Clerk has been removed?

After removing the "Clerk" installation from my project and deploying it to production, I encountered an error that is preventing me from going live. Despite not finding any references to Clerk in my app, I am still facing this issue. Can anyone assist me ...

Is it possible to effectively handle SSG, i18n, and dynamic routes in NextJS version 14 by solely utilizing the pages router?

As we strive to upgrade Next.js from version 12 to 14, the process of configuring i18n in a statically generated app using dynamic catch-all routes with the pages router has become unclear. The main issue arises when attempting to set the i18n configurati ...

What is the correct way to iterate through a list of images fetched with getStaticProps and display them within the same component?

What is the proper way to map a list of images returned using getStaticProps? I had successfully implemented this by passing a prop to the gallery component in another page. However, I now want to consolidate all the getStaticProps code within the gallery ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Is there a way to keep a div element anchored at the top of the page until I reach the bottom and then have it stick to the bottom as I continue

I have a question that I hope is clear enough! On my webpage, there is a div at the top that I want to move to the bottom when I scroll and reach the end of the page. Hopefully, you understand what I'm trying to achieve! If anyone has any ideas, I&ap ...

The jQuery scrollLeft function seems to be stuck and not working correctly

I have a container div with a ul inside of it set up like this CodePen: http://codepen.io/example/123 Why won't the scroll feature work? HTML: <div id="container"> <ul class="list"> <li>apple</li> <li>orange& ...

Position divs to be perfectly aligned and centered

I'm in the process of creating a webpage and facing challenges with aligning my divs properly, specifically the animated company logos. I want them to be positioned side by side rather than on top of each other, with space in between to fit the layou ...

Having trouble using jQuery's .off() method to remove an event handler?

I'm facing an issue with my jQuery code where the .off('click') method doesn't seem to be working. I've tried removing the event binding from '.reveal-menu', but it's not working as expected. The initial animation wo ...

Why isn't the AngularJS injected view resizing to fit the container?

As a novice delving into a project in the MEAN stack, I'm encountering inconsistent HTML previews. When I view it independently versus running it from the project, the display varies. Here's the intended appearance (in standalone preview): imgu ...

Trouble with saving the positioning after drag and drop

I am currently facing an issue with my drag-and-drop script where the coordinates of positioned relative divs are not being saved in the same position when I reload. These divs are contained within a container with specific height and width, restricting t ...

Is it possible to display partial html templates by accessing the local url and blending them with the main index.html file?

Is there a way to view partial HTML templates locally without copying them into the main index.html file? I'm looking for a solution that allows me to access my partial templates through a local URL without having to manually paste them into the main ...

Deciding Between Two Columns or One Column for Your JQuery Accordion

I am currently working on customizing an Accordion that is too large in height for my liking. My goal is to convert the single column layout into a two-column display, side by side. Having multiple items in one column results in excessive height, hence t ...

Why Isn't Formik onChange Updating the Field Value?

Hello everyone, I'm encountering a strange issue with a Formik form that uses Select fields. Here's what I would like it to do: Select A allows you to choose a County Select C allows you to select a City. Whenever a user picks a different opti ...

The process of inserting a CSS file into a CodeIgniter project

Hey there, I'm struggling to load a CSS file in Codeigniter. Can someone please guide me on how to do it? Below is an overview of the Codeigniter sample Directory Structure: views models controllers assets a) stylesheets b) javascript c) images Conf ...