The implementation of CSS in one React component has an impact on the functionality of the Ant Design Select component in

I've run into a puzzling issue where importing CSS styles in one React component is impacting the appearance of Ant Design's Select component in another component. Let me break down the scenario:

The setup involves two React components, namely Parent and MyCompThatHaveCss, organized as shown below:

// Parent.tsx
import Child from "./Child";
import MyCompThatHaveCss from "./MyCompThatHaveCss";

export default function Parent() {
  return (
    <div>
      <Child />
      <MyCompThatHaveCss />
    </div>
  );
}

// MyCompThatHaveCss.tsx
import './style.css';
import { Select } from 'antd';

export default function MyCompThatHaveCss() {
  return (
    <div>
      <p>Component with CSS styles</p>
      <Select options={[{ value: 'Option 1', label: Option 1 }]} />
    </div>
  );
}

In MyCompThatHaveCss.tsx, I bring in CSS styles using import './style.css';, while also utilizing Ant Design's Select component.

Nevertheless, I've observed that the styles from style.css are affecting the Select component within MyCompThatHaveCss, along with other Select components across the application - this is not what I intended.

Specified CSS styles:

/* Make dropdown content width by content in it*/
.ant-select-dropdown {
  width: max-content !important;
}

/* For make text not off screen when text too long */
.ant-select-item-option-content {
  white-space: pre-wrap !important;
}

How can I ensure that the CSS styles imported in MyCompThatHaveCss.tsx don't impact the styling of the Select component from Ant Design, restricting them to only apply to the specific component's styles?

I'm open to any insights or solutions to tackle this issue. Thank you!

Answer №1

The reason for the issue is that you are modifying the css of the antd select component without specifying its exact location.

One solution could be to assign classes to the parent element of the antd select and then apply the css styles:

// MyComponentWithCustomCss.tsx
import './styles.css';
import { Select } from 'antd';

export default function MyComponentWithCustomCss() {
  return (
    <div className="container">
      <p className="paragraph">Component with custom CSS</p>
      <Select options={[{ value: 'Option 1', label: 'Option 1' }]} />
    </div>
  );
}

Then, you can apply the css like this:

/* Set dropdown content width based on its content */
.container .ant-select-dropdown {
  width: max-content !important;
}

/* Prevent text from going off-screen when it's too long */
.container .ant-select-item-option-content {
  white-space: pre-wrap !important;
}

This should help resolve your problem. Hope it works for you :)

Answer №2

I was able to find a solution that partially fixed the issue with the CSS style replacement for now.

The fix involved adding some code to the Select component in antd:

<Select
  dropdownStyle={
    { 
      width: "fit-content", 
      whiteSpace: "pre-wrap" 
    }
  }
/>

Although this workaround solves the width problem in most scenarios, it doesn't work as intended when the screen size is decreased. Instead of maintaining a fit-content width, it reverts to a max-content width.

If anyone has a more comprehensive solution to offer, I would greatly appreciate it. Thank you!

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

Aligning two lines next to a radio button using HTML and CSS

I'm facing a challenge where I want to align two lines in the middle of a radio button. Despite my efforts, I am able to line up the top line but struggling with the bottom one. I prefer not floating the radio button as it's being styled using a ...

The media query in Css3 is not functioning as expected when using max-width

Struggling to hide a specific element when the screen width reaches 980px or less using media queries. Despite my attempts, the element continues to display. Oddly enough, if I use a media query with min-width instead of max-width, the element disappears ...

Rendering components recursively using a tree structure for menu items

I've designed a component that enhances user experience by adding an extra dropdown selection box whenever a key within an object corresponds to another object. Let's take a look at an example object: { a1: { x1: 1, x2: 2, x3: 3, ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

How come my flex-box navigation bar is not collapsing as I shrink the browser window size?

I'm currently experimenting with FlexBox to enhance the design of my website, specifically focusing on creating a responsive and collapsible navigation bar for mobile users. I'm encountering issues with the flex commands in the .nbar class not wo ...

including a code snippet within a dropdown menu or embedding it in a clickable button

Hey there, my name is Wouter Sanders and I am currently learning to code! I recently finished creating a RAL color picker for a project I'm working on. The only issue I've run into is trying to embed the code in a menu or button so that it doesn ...

Understanding Typescript event handling in React

Encountering issues when attempting to build my React/Typescript app using the MouseEvent type in an event handler: private ButtonClickHandler(event: MouseEvent): void { ... } The error message received is as follows: error TS2322: Type '{ onCl ...

Adjustable textarea with automatic height based on content and line breaks

Imagine you have a textarea with text that includes line breaks. If you style it like this: textarea { height: auto; overflow: hidden; resize: none; } Upon loading the page, the textarea will only adjust its height based on the content until it enc ...

What is the trick to have a CSS element overflow the boundaries of its containing div entirely?

Currently, I have a JS Fiddle project where I am attempting to achieve a specific effect. In the project, there is a circle positioned at the center of a div. When the script runs, the circle expands evenly in all directions until it reaches the borders on ...

Bootstrap 5 dropdown toggle displaying incorrect menu

I am currently working on a website project using Bootstrap 5. In the navigation bar of my site, I have implemented a dropdown menu with multiple submenus that dropend. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" ...

Experience the power of Nextjs paired with Material UI and a personalized global stylesheet for

I am utilizing Next.js 9.3 with the export feature to produce a static site. The setup for Material UI follows this example implementation (https://github.com/mui-org/material-ui/tree/master/examples/nextjs). In addition to Material UI, I have a global st ...

Generating a PDF from a CSS3 multi-column layout with the help of snappy (a wrapper for wkhtmltopdf)

I am attempting to create a PDF with three columns using barryvdh/laravel-snappy and wkhtmltopdf. Since the text that will populate these columns varies in length, I need a method that allows the text to flow freely within the columns. I have attempted to ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

Using the position property of relative on a DIV element causes a gap to appear between the DIV and the next

Two div elements are placed consecutively. When I move the first div using position: relative and top: -60px, it creates a gap between them. Take a look at this example here: https://codepen.io/dusannis/pen/oNgBpoK If you notice, there is a noticeable ga ...

Mastering the integration of an array of objects with the ej2 Syncfusion data grid

Trying to figure out how to map a complex array of objects into the ej2 Syncfusion React data grid. Here is an example of my array: [ { "id_team": "1",, "team_name": "Testing", "adviser": " ...

Hierarchical ordered list with Material UI styling

I wanted to create a list in the following format: 1. xxxxx 2. xxxxx a. xxxxx b. xxxxx 3. xxxxx 4. xxxxx a. xxxxx b. xxxxx The data for this list will be sourced from a react state variable and will need to be mapped accordingly. The exact str ...

Implement vertical scrolling functionality in Material Grid widget

I'm working with a Material Grid that contains multiple items. <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <Bo ...

having trouble with developing a dropdown menu using jquery

I'm currently creating a drop-down menu for my website and here is the code I'm using: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html dir="ltr"> <head> <met ...

Tips for ensuring consistent spacing between font icons within a navigation bar when using text with font icons as links

Below is the code I have implemented for a navigation bar: body { margin: 0; } .navbar { display: inline-block; background-color: #495057; width: 100%; } .navbar ul { list-style-type: none; text-align: center; float: left; } .navbar ul ...

Unsuccessful response: An error was encountered with status code 400 in the new ApolloError

I'm currently developing an application that utilizes NestJS for the backend with GraphQL and Postgres, while the front end is in Next JS. I've encountered an error when trying to call a mutation from the front end. Out of all the mutations, onl ...