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 jQuery Cycle causing images not to load in IE all at once, leading to blinking

When using the jQuery Cycle plugin in IE8 (as well as other versions of Internet Explorer), I am encountering an issue. My slideshow consists of 3 slides, each containing a Title, Description, and Image. The problem arises when viewing the slideshow in I ...

What is the best way to display a collection of square Views in a FlatList in a react native application?

How can you create a scrollable square grid with two columns of squares in a FlatList using react-native and ensure it is responsive to different screen sizes? Which CSS properties in react-native are necessary to achieve square shapes for each <Item/& ...

Guide on integrating angular-schema-form into an Ionic 2.0 project using typescript

Recently, I embarked on creating an app with Ionic from scratch and decided to integrate the framework. While I faced no issues executing the example on a webpage, I encountered difficulties when attempting to do so with Ionic. To kickstart the project, ...

Having trouble publishing project on Vercel because of a naming issue

Whenever I try to deploy a project on vercel, I encounter an error stating that the project name is not valid. The specific error messages are as follows: Error: The name of a Project can only contain up to 100 alphanumeric lowercase characters and hyphe ...

Create circular shapes using the border-radius property

I've been experimenting with converting some divs using border radius and I've almost got it, but sometimes they end up looking like 'eggs' haha. Here is the CSS code I'm using: #div{ /*central div*/ position:absolute; t ...

Error Detected: An unhandled error occurred, triggering a promise rejection: TypeError: The super expression must be either null or a function in Angular version 6

Upon deploying the application on AWS Elastic Beanstalk, an error has surfaced. While the build and deployment processes were successful, one module is giving a Super Expression error. The other modules are functioning correctly, and everything works fine ...

A step-by-step guide to customizing the Material UI Chips delete SVG icon to appear in white color through

Using a Material UI component, I added a custom class to my chip. Attached is a screenshot showing what I mean. Currently, I am attempting to change the color of the cross button to white. After inspecting the element, I discovered that it is an SVG ico ...

Tips for passing parameters into a history push action

I'm currently working on a click handler that should redirect the page when an item in the list is clicked. Goals: onRowClick: (rowIndex) =>this.props.history.push( {pathname: '/tickets', param: rowIndex[0]}; However, it seems like the ...

Displaying error messages with react-hook-form in a React application

How can I implement validation to display an error message for the phone number field (using helperText with a minimum of 10 and maximum of 10 characters) and also show an error message if submitted without exactly 10 numeric digits? import ReactPhoneInp ...

Upon page load, a dazzling SVG file will flicker before being adorned with CSS styles

I'm experiencing an issue with an SVG arrow icon on my webpage that flashes quickly across the entire screen upon page load before settling into its proper size and placement. I've tried using CSS to initially hide the icon and then reveal it aft ...

Enhance your React Data Table Component by incorporating or modifying Material Ui class names

I am looking to enhance my React Data Table by incorporating Material Ui classes to improve its integration with the rest of my application. Although it was mentioned in the documentation that you can override the CSS using styled components, I have not be ...

Tips for keeping the Menu bar at the top of the page while scrolling from the middle

I came across a technique mentioned here that I wanted to implement. I used this jsfiddle link (which worked well) to create my own version http://jsfiddle.net/a2q7zk0m/1/, along with a custom menu. However, now it seems like it's not working due to a ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Modifying the WP FlexSlider plugin to eliminate the previous and next side panels

Is there a way to either reduce the width of the slider's prev/next sides or remove these panels while keeping the arrows to cycle through slides? These elements appear to be within ul.flex-direction-nav. I attempted using ul.flex-direction-nav { dis ...

Enhance your SVG progress circle by simply selecting checkboxes

I have a unique system with 5 checkboxes that act as a To-Do list. When I click on each checkbox, the circle's diameter should progressively fill up in increments of 1/5 until all 5 checkboxes are completed. The order in which the checkboxes are click ...

React and Material-UI require that each item in a list have a distinct "key" property assigned to it

While rendering, I encounter the following error/warning: Warning: Each child in a list should have a unique "key" prop. Check the render method of `App`. See .. for more information. in ListItemCustom (at App.js:137) in App (created by WithStyle ...

What is the best way to determine the width of tables - in the HTML code or using a CSS class?

I recently came across some advice suggesting that a website should still be able to function properly even if the CSS files are not loaded. What approach do you think would work best in this situation? Would it be more effective to use <table width=50 ...

Is it recommended to perform all data fetching within getStaticProps in NextJS?

When working with NextJS and static site generation, it is essential to handle all network requests within the getStaticProps function. I have successfully moved all my fetch calls inside getStaticProps. However, I am now facing a challenge when it comes ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...