-2

A bit of a noobie question here but I have just started working with React and also in a large project and I've noticed that both class and className cannot be used on all elements and components. More specifically, custom components. This has forced me to put the className in a div container but this feels like a bad practice.

enter image description here

This is very strange behavior for me as I am coming from an Angular and Vue background where class or [class] can be placed on most anything and add classes to a component or element

What situations would cause class and className to not be allowed on a component/element in the template?

Ian Steffy
  • 1,234
  • 3
  • 18
  • 45
  • 2
    `class` is a keyword in JavaScript so it can't be used in JSX. [Use `className` instead](https://reactjs.org/docs/faq-styling.html) to add CSS classes to a JSX element. – David Jul 08 '22 at 12:02
  • `class ` is a keyword in `javascript` and `JSX` is an extension of javascript. That's the principal reason why `React` uses `className` instead of `class`. similar stack overflow article [here](https://stackoverflow.com/questions/46989454/class-vs-classname-in-react-16) – Omar Dieh Jul 08 '22 at 12:05

1 Answers1

1
  1. You can't use class keyword on JSX elements, this is one of few restrictions of jsx.
  2. className error can be caused because of props and types. If you are using className on div, for example and it throws some error, means some package may not be installed, or if you are using react < 17, you forgot to import react module.

Could you be more specific, if you are using typescript and some ui library, like MUI? From what you are saying, it is hard to determine why className causes an error.

Tigran Petrosyan
  • 524
  • 4
  • 14
  • I'm not asking for a solution to my specific coding situation. I am searching for situations for when class and className would not be allowed. If these two reasons are the two main reasons that this would occur, then my question has been answered. – Ian Steffy Jul 11 '22 at 10:46
  • Scratch that. I've added an example where a `div` and a `CustomComponet` both try to add classes. The `CustomComponent` is unable to accept any `class` or `className`. I am using Tailwind for my ui lib – Ian Steffy Jul 11 '22 at 14:12
  • And you are using JavaScript or TypeScript? And how you custom component looks? Div should allow className without problem, But your custom element may need a porp className, if youa re using typescript. I can't say for sure, until I see the code. – Tigran Petrosyan Jul 11 '22 at 14:20