Tips on adding conditional styles in Next.js

This is my attempt:

function ChangeStrokeToTextAndImage(properties: ChangeStrokeToTextAndImageProps) {
  return (
    <div
      className={
        styles.container0 + " " + properties.isLightGreenBackground == true
          ? styles.isLightGreenBackground
          : " "
      }
    >

If the condition applies, I want to apply styles.container0, and if

properties.isLightGreenBackground
is true, then also apply styles.isLightGreenBackground.

The syntax seems correct, but for some reason the style is not being applied. Any idea why?

Answer №1

Enclose the conditional part in parentheses:

function Stroke2TextAndImage(props: Stroke2TextAndImageProps) {
  return (
    <div
      className={
        styles.container0 +
        " " +
        (props.isLightGreenBackground === true
          ? styles.isLightGreenBackground
          : " ")
      }
    >
      ...
    </div>
  );
}

Your current code will be interpreted as follows:

if(Boolean(styles.container0 + " " + props.isLightGreenBackground) === true) 
    styles.isLightGreenBackground
else
    " "

Here is a quick demonstration:

console.log('foo' + ' ' + 'bar' == true ? 'hey' : 'there') // 'there'

console.log('foo' + ' ' + ('bar' == true ? 'hey' : 'there')) // 'foo there'

For more information, please visit: Operator Precedence

Recommendation: Consider using a utility library like clsx or classnames if you encounter multiple similar cases to prevent potential issues in the future.

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

is it possible to adjust the height of a tableRow in mui?

I recently created a table component using Mui. I've been attempting to adjust the height of the tableRows, but so far I haven't had any success. Below is my code snippet: import React, { memo } from "react"; import { ActionItemType, ...

Choose the initial p tag that includes an image, based on the content of another div

I am trying to figure out how to manipulate the code on my website: <div class="the-post-thumbnail"> <img src="" alt="" width="" height="" /> </div> <div class="post-body"> <p><img src="" alt="" width="" height="" ...

What is the reason that Vercel's function log is not displaying console.log?

I noticed this issue with the server method called generatePostAnimation https://i.sstatic.net/j6Nua.png There are no log lines being produced. I have several console.log statements like this: console.log('Images loaded') What am I overlookin ...

Tips for sharing a React component with CSS modules that is compatible with both ES Modules and CommonJs for CSS modules integration

Some frameworks, like Gatsby version 3 and above, import CSS modules as ES modules by default: import { class1, class2 } from 'styles.modules.css' // or import * as styles from 'styles.modules.css' However, other projects, such as Crea ...

Conceal a Component within an Embedded Frame

Hey there! I've been attempting to hide a header within an iframe, but it seems like my code isn't doing the trick. Could someone take a look and help me diagnose why the header is still visible? Thanks in advance! <iframe id="booking_iframe" ...

The CSS in Django seems to be malfunctioning on various pages, particularly on header elements

My CSS file is linked in 'main/static/css/style.css' and my pages are located in 'main/templates/main/pages.html'. However, the CSS does not seem to be working properly for some pages; for example, the h2 tag is not taking on the specif ...

Crafting a responsible table design with the help of grid layout techniques

Is there a way to create a table that can adjust its rows and columns based on the container width or when resized? https://i.sstatic.net/xeZjl.png https://i.sstatic.net/kdpJC.png I attempted to use grid-gap in the background, but it resulted in empty red ...

The presence of whitespace is causing disruptions in the text alignment within div elements

I've noticed some unwanted white space on my website when viewing it in Chrome and Internet Explorer. It's interrupting the flow of text and I can't figure out where it's coming from. Can someone help me locate and remove this pesky wh ...

Adjusting the height of a card in Reactstrap

I am currently exploring Reactstrap and aiming to ensure a specific Card adjusts according to the size of the window by setting its aspect ratio using percentages rather than pixels. Interestingly, while adjusting the width works as desired, I'm faci ...

Manipulating CSS animations through JQuery

Currently, my animation is triggered by a :hover event. However, I would like to change it so that the animation starts when a button is clicked. Can someone guide me on how to manipulate the CSS using JQuery? //CSS .mouth{ top: 268px; left: 273px; ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

Misalignment of Font-awesome icons in the footer section

I've implemented a footer on my website. My goal is to have the icons centered both vertically and horizontally, with the colored area: Always positioned at the bottom of the screen No taller than the icons themselves Here's the code snippet: ...

The next-auth/discord callbacks do not make any changes to the data

Currently, I am utilizing the next-auth/discord and facing an issue with the session callback not setting the user id to the session property as expected. [...nextauth].js import NextAuth from "next-auth/next"; import DiscordProvider from " ...

Which programming language is best suited for this task?

Seeking assistance with changing an image inside a div to another image with a simple mouse click. Wondering if this can be achieved through CSS or if jQuery would be the better option. Here is the code snippet: <div id="slideshow"> <img ...

When aligning to the right, input box does not wrap

Is there a way to prevent an input box from displaying on a lower line than the menu when using CSS to create a one line menu floated to the right? This is the CSS code being used: <style type="text/css"> #nav { margin:0; padding:0; lis ...

When refreshing, the useEffect async function will not execute

Upon page load, the getImages function is intended to run only once. After refreshing the page, both tempQuestionImages and questionImages are empty. However, everything works perfectly after a hot reload. I am utilizing nextJs along with Firebase Cloud ...

Customize your webpage's style to reflect your unique identity with user

Is there a way to allow users to customize the style of a webpage? I know I need multiple CSS files, but how can I implement the code that enables this customization based on user preferences? ...

The issue of causing a "window is undefined error" persists even after attempts to fix it, ultimately rendering it out of scope

When I try to initialize a const, I encounter a "window is undefined" error in nextjs. To resolve this issue, I have attempted the following code: if (typeof window !== "undefined") { const web3Modal = new Web3Modal({ network: "mainnet&q ...

What is the best way to manipulate the size and orientation of an image upon hovering over

I'm struggling to figure out how to simultaneously rotate and scale a .png file when the user hovers over it. Currently, it only scales when I hover on the picture. I understand that the scale property overwrites the first transform but I can't s ...

Gathering information from the server once it has completed its processing phase

Looking to retrieve data from my server after processing it. Specifically, I want to transfer the processed information to the front end. Situation: A document gets uploaded to Google Cloud, data is extracted and stored in Firestore, then that extracted d ...