# Id selector in react css modules
Asked Answered
F

3

12

I'm using React Css modules for styling my react app.

I have some html elements with id attribute and I want to style them using the css id selector and not a class selector. Is that possible with react css modules? For example.

This is an example of css, I'm going to call it Button.modules.css

#specialButon {
 margin: 5px;
}

.notSpecialButton {
 margin: 5px;
}

And this is an example of react component

import style from './Button.module.css';

function Button() {

 render(
  <div>
   <button id="specialButon">Special<button>
   <button className={style.notSpecialButton}>Not Special<button>
  </div>
)

export default Button

Could you tell me, How can I use de id selector to apply style elements?

Thanks you.

Francesfrancesca answered 14/7, 2021 at 9:53 Comment(1)
The same way you apply a class: id="style.specialButon"Uralic
A
3

For that, you can use global CSS in React which is generally in App.js. But is general to use className in module CSS.

Augusto answered 14/7, 2021 at 11:14 Comment(0)
G
12

It's a bit late, but the accepted answer is actually not a right one. You can definitely use id selectors with CSS Module!

In your case, just changing it to the below will do :)

<button id={style.specialButon}>Special<button>

or

<button id={style['specialButon']>Special<button>
Gild answered 18/8, 2022 at 10:57 Comment(2)
And referring to an id within CSS module remains the same, correct? As in, #id{….} ?Dunnite
this only works as you suggest because actual CSS id uses camel case. If you use proper kebab case like #special-button then it would only work like style['special-button']Passbook
A
3

For that, you can use global CSS in React which is generally in App.js. But is general to use className in module CSS.

Augusto answered 14/7, 2021 at 11:14 Comment(0)
M
0

Yes its totally OK to use id's in CSS Modules.

Component.js

<button id={style.specialButon}>Special<button>
or
<button id={style.specialButon}>Special<button>

style.module.css

#specialButon{
margin: 5px;
color:red;
}
Mccrea answered 16/8, 2023 at 11:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.