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.

https://i.sstatic.net/qCabN.png

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

https://i.sstatic.net/ijzjL.png

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 is the method for altering font color in HTML?

Here is the section of my code that I am struggling with: <p style="font-family:'impact', color:red"> something </p> The issue I am facing is that I am unable to use both the color and the font propert ...

Guide to positioning a toolbar within an element when hovering over it in HTML with the help of JQuery

function attachMenuBar() { $('body').on('mouseover mouseout', '*:not(.printToolBar)', function (e) { if (this === e.target) { (e.type === 'mouseover' ? setMenuBox(e.target) : removeMenuBox(e.t ...

Ways to show the existing value of a <select> in a label without altering the function

I currently have a label that changes to display the selected option from a dynamic select dropdown, but it only updates when the selection is changed. I would like it to also display the current value when the page first loads. I attempted to change &apos ...

Issue: The type 'void' cannot be assigned to the type 'ReactNode' in the array.map() function

Having trouble with my function call error within the practice setup in App.tsx. My expectation of array.map() being compatible with TypeScript seems to be incorrect. The generated HTMLElement from this map is not displaying on screen. Any suggestions on ...

What is the best way to incorporate a react component into a Next.js project?

Looking to integrate a date picker that can select dates and ranges for my nextJS project, but struggling with adding components based on the online code. After running npm install react-day-picker --save, I came across this code: import React from ' ...

Interactive YouTube Video Player that keeps video playing in original spot upon clicking the button

Currently, I'm working on a project that involves combining navigation and a video player within the same div container. Here is an image link And another image link The concept is that when you click on one of the four boxes, a new video will appe ...

A tutorial on how to customize the hover effect for TableHead Column Identifiers in MaterialUI by adjusting

I'm struggling to customize the appearance of child th elements using the TableHead component from MaterialUI. While I've been successful in modifying various properties, I'm facing difficulty in changing the hover color. Below is the snipp ...

The rounded corners feature of PIE.htc does not seem to be functioning properly on Internet Explorer

Check out my code below: http://jsfiddle.net/parag1111/s5RLb/ Make sure to place PIE.htc in the CSS folder. I've already included the necessary JS and behavior for PIE.htc. Please provide any additional suggestions to ensure compatibility with IE8 a ...

Having difficulty navigating the website due to the inability to scroll

I am experiencing a problem on this website where I am unable to scroll. Visit www.Batan.io After loading the website for the first time, the trackpad (mac) works fine initially but then the scroll function stops working. Although the sidebar works, chan ...

Struggling to incorporate this script tag into my next.js application and encountering some difficulties

If you want to integrate EmailJS into your website, simply add the code snippet below before the closing tag, making sure to replace "YOUR_USER_ID" with your actual user ID: <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com@2 ...

Is there a workaround for retrieving a value when using .css('top') in IE and Safari, which defaults to 'auto' if no explicit top value is set?

My [element] is positioned absolutely with a left property set to -9999px in the CSS. The top property has not been set intentionally to keep the element in the DOM but out of the document flow. Upon calling [element].css('top') in jQuery, Firef ...

Ways to switch text on and off smoothly using transitions

I have created a webpage where text starts off hidden but has a visible heading. When you click on the heading, the text is revealed below. I am putting the final touches and aiming to make the text slide in smoothly. I am using Javascript for toggling ins ...

Change the destination of an iFrame upon user click

Is it possible to redirect an iFrame to a different HTML page when clicked by the user? I have an iFrame that is essentially an HTML page. When I click on the iFrame, I want it to take me to another HTML page. This is my code: h1 { ...

The lobster custom font is malfunctioning in Internet Explorer

I am trying to use the unique font called lobster. After downloading the lobster.woff2 file, I stored it in the font folder. In my custom CSS, I added the following: @font-face { font-family: 'Lobster'; font-style: normal; font-weight: 40 ...

Uploading multiple images using Next.js

I am facing some issues while trying to upload multiple images and retrieve their paths in the response. When I upload images named like fundamental.png and starter.png, they are being saved on the server with unexpected names such as fundamental.png and f ...

What is the best way to reduce the size of a Bootstrap card image back to its original dimensions when

I am currently experimenting with a bootstrap card using HTML, CSS, and Bootstrap. My main focus right now is on how to shrink the image when hovering over it. The .card-header-img has a fixed height of 150px that I do not want to modify. What I want to a ...

What is the reason for the disappearance of unordered list bullets when using padding: 0?

Updating an older website that contains numerous unordered lists has presented a challenge. When the padding is set to 0, the display markers on the unordered list disappear. The root cause of this issue was traced back to the CSS setting *{padding: 0; ma ...

Push Button Unleashes a Cascade of Buttons

After creating a dropdown button, I encountered an issue where replicating it multiple times resulted in all the buttons on the page opening simultaneously. I initially thought that wrapping the button in a class called "dropdown" would prevent this from h ...

Tips for Providing a Generic Type to a Component Imported Using Next.js Dynamic

There is no issue with this code snippet: import DatasheetContainer from '@/uikit/detailed-view/DatasheetContainer'; const DetailedView = () => { return ( <Page> <PageBody direction="row" bgColor="white&qu ...

prevent unnecessary duplicate database queries for generating metadata in the upcoming 13 or 14 instances

In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata. However, a drawback of this approach is that because of the separation of logic, fetching data base ...