The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well!

I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example:

import { ButtonHTMLAttributes } from 'react';

type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
  title: string;
  backgroundLowOpacity?: boolean;
};

export function Button({ title, backgroundLowOpacity, ...rest }: ButtonProps) {
  return (
    <button
      {...rest}
      type="button"
      className={`${backgroundLowOpacity && 'bg-gray-100'}`}
    >
      {title}
    </button>
  );
}

This is the component setup. Now, when I try to use className in the parent component, it doesn't work as expected.

<Button title="Sign up" className="bg-purple-500" />

Unfortunately, this doesn't apply the color purple to my button.

Answer №1

Essentially, in line 13 you are initializing a new className property, which will replace the existing className property from the spread operator ...rest. The correct method is as follows:

import { ButtonHTMLAttributes } from 'react';

type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
  title: string;
  backgroundLowOpacity?: boolean;
};

export function Button({ title, backgroundLowOpacity, className, ...rest }: ButtonProps) {
  return (
    <button
      {...rest}
      type="button"
      className={`${className} ${backgroundLowOpacity && 'bg-gray-100'}`}
    >
      {title}
    </button>
  );
}

This way, any className you provide to your component will be included first, followed by checking if backgroundLowOpacity is also passed in before applying additional styling.

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

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

Leveraging databases during each deployment iteration

There is a growing trend among modern cloud deployment services such as Vercel, Netlify, and Linc to deploy web apps on every commit for pull requests. This practice is particularly beneficial for frontend code. However, it has also become popular for fra ...

Using Typescript and Next.js to handle error messages returned from Axios responses

My Next.js application makes an API call to validate a registration form. The server returns error messages in the following format: {"message":"The given data was invalid.","errors":{"email":["The email has alr ...

"Unearthing a skeleton within the client component while the server action unfolds in next

One of the challenges I'm encountering involves a client component that initiates a server action. The server action returns a result, which triggers an update in the UI. Take a look at the code snippet provided below for reference export default func ...

Rearrange elements within a div by clicking a button

I want to shuffle div elements with a click of a button using a dissolve animation in HTML5. An example of what I am looking for is similar to this website When you scroll on the page, there are links such as All, Intro, Solution. Clicking on any link sh ...

Getting the content inside a div tag with selenium in python

Is there a way to retrieve the content within the specified div tag? I attempted copying and pasting the xpath, but when attempting to print the contents of the div, it did not work. div = driver.find_element_by_xpath('//div[@class="sold_out_tag"]&ap ...

Is there a way to adjust the positioning of an image within a <div> element?

I'm attempting to vertically align an image within a horizontal menu bar. My goal is to adjust the padding/margin of the image using inline CSS. However, I've noticed that when I add margin-top or padding-top, it affects the positioning of all m ...

Execute the unknown function parameter

Trying to figure out how to convert an argument into an anonymous function, but struggling to find clear instructions. I know how to cast on variable assignment, but unsure if it's possible and how. Working with lodash where the typings specify the a ...

Grid items in Material UI are not positioned next to each other

I am encountering an issue with the Grid component in material-ui. The grid items are currently stacking below each other instead of beside each other, and I'm unsure of what is causing this behavior. My intention is for the grid items to stack on top ...

Tips for integrating tsconfig with webpack's provide plugin

In my project, I have a simple component that utilizes styled-components and references theme colors from my utils.tsx file. To avoid including React and styled-components in every component file, I load them through WebpackProvidePlugin. Everything works ...

Ensure that typescript examines the context of 'this' within unrestricted functions

I'm having trouble getting Typescript to detect an error in the code snippet below: function foo() { console.log(this.x.y) } foo() When I run it using npx ts-node a.ts, there are no Typescript errors displayed, but it naturally fails with TypeEr ...

Delay the occurrence of a hover effect until the previous effect has finished executing

As I hover over an element, the desired animation is displayed while hiding other elements on the page. The challenge I'm encountering is that if I quickly hover over many divs, the animations queue up and hide the divs sequentially. I want only one ...

Although server-side rendering is utilized with react-query, JSON data continues to be displayed in the network tab

As per my understanding, the only way to conceal a JSON return from an API call is through server rendering. I have implemented this on all pages using Next.js; however, the network tab still displays a JSON with my data on pages where useInfiniteQuery and ...

React js: Caution - Ensure each child within a list is assigned a distinct "key" property

One of the most frequently asked questions in React is regarding the key prop in the Todo component. Despite passing the id and using it as the key, some users still encounter errors. Various solutions have been attempted without success. Even though the ...

Infinite scrolling with a dynamic background

Hi there, I am working on my website and trying to create a smooth transition between sections similar to the one demonstrated here:. The challenge I'm facing is that the backgrounds of my sections cannot be fixed; they need to have background-attachm ...

Creating XML templates in Angular 7: A comprehensive guide

How do I pass XML values in Angular 7 when the API requires this specific format of XML code? -modifydata "<datasets><dataset select=\""always\""> <replace match=\""Letter/@FName\"" value=\""Nazeeeeeeeeeeeeer\" ...

The client's request experiences a 502 error after a duration of 2 minutes

My React website sends a GET request from the client using axios to a proxy server that is waiting for a callback from the payment engine via EventEmitter. The problem arises when the GET request fails after 2 minutes with a 502 error. I attempted to reso ...

Calculate the difference of two inputs using ReactJs for project balance

Hey there, I'm currently diving into the world of ReactJS and have hit a stumbling block. I've set up two input fields - one for income and one for outcomes. My goal is to dynamically calculate the balance (income - outcome) without needing to h ...

How can I design a Typescript interface that accommodates both strings and other data types?

I am working on designing an interface that allows for an array of objects and strings to be stored. For instance: const array = [ '', {id: '', labels: ['']} ] I attempted to achieve this using the following code: export ...

How to switch a particular div (identified by its ID) in a React component

I've encountered an issue with my site that is using post-components to display articles in a feed. Within the component, there's a button that triggers a modal to open onClick. I've successfully implemented useState to toggle the modal, but ...