TransWikia.com

Styling react-select with CSS modules works on Sandbox but not on local machine

Stack Overflow Asked by Willege on November 7, 2021

The ‘Using ClassNames’ section of react-select docs states that using the className and classNamePrefix props

ensures compatibility with styled components, CSS modules and
other libraries.

In this CodeSandbox, with CSS modules and node-sass, it seems to work. However, if I replicate the following code on my local machine in a create-react-app, it doesn’t work. My CRA uses the Typescript template. Is that the problem? Everything else is just the same.

Select.module.scss

.select {
  outline: 1px solid red;

  .select__control {
    background-color: salmon;
  }
}

Select.tsx

import React from 'react';
import RS from 'react-select';
import style from './Select.module.scss';

const options = [
  {label: "hi", value: "hi"}
]

function Select(props: any) {
  return (
    <RS
      options={options}
      className={style.select}
      classNamePrefix={style.select}
    />
  )
}

export default Select;

App.tsx

import React from 'react';
import Select from './Select';

function App() {
  return (
    <div className="App">
      <Select />
    </div>
  );
}

export default App;

One Answer

I could make it work here by doing:

Select.module.scss

.select {
  outline: 1px solid red;

  [class$="-control"] {
    background-color: salmon;
  }
}

Select.tsx

import React from 'react';
import RS from 'react-select';
import style from './Select.module.scss';

const options = [
  {label: "hi", value: "hi"}
]

function Select(props: any) {
  return (
    <RS
      options={options}
      className={style.select}
    />
  )
}

export default Select;

Basically, I removed classNamePrefix from react-select component and changed .select__control to [class$="-control"], which matches all classes ending with -control.

The problem here was because css loader was adding a hash in my classnames eg {select: "styles_select__SQ71h", select__control: "styles_select__control__xcj2p"}.

Answered by guijob on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP