Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the className attribute take on the role of the id attribute in Reactjs?

Since id attributes are rarely used in Reactjs components due to the fact that id attributes imply that the component will not be reused, then are className attributes used instead of id's? If this is the case, then what is the Reactjs equivalent of the class attribute in HTML?

like image 768
Dipen Avatar asked Feb 14 '15 18:02

Dipen


People also ask

What is className attribute in React?

In class-based components, the className attribute is used to set or return the value of an element's class attribute. Using this property, the user can change the class of an element to the desired class.

Why does Reactjs use className over class attribute?

Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute.

How do I use className in Reactjs?

className. To specify a CSS class, use the className attribute. This applies to all regular DOM and SVG elements like <div> , <a> , and others. If you use React with Web Components (which is uncommon), use the class attribute instead.

Can we use ID in react JS?

Let's start with id attribute in React JS and here we have used id attribute to access one of the elements in a React Component. In this IdComponent component, we are performing the following operations: When a user focuses on a text field, it will change the border-color to blue and backgroun-color to light black.


2 Answers

className is used for class names for CSS styling, just as elsewhere.

You can give something a unique className for styling purposes the same way you might give otherwise give it an id, sure, but that doesn't really imply anything else for other className usage, which can never really be a direct equivalent to id because className can contain multiple class names, none of which have to be unique. (There are also pretty good reasons not to use id for styling, regardless of React).

A more usual reason not to give something an id with React is that you rarely need to add hooks to go and look up an element from the real DOM, as you can use state or props to control rendering changes which do whatever dynamic stuff you need to do, and if you do need to go grab an element, you can give it a ref name and use getDOMNode() on it.

like image 120
Jonny Buchanan Avatar answered Sep 20 '22 23:09

Jonny Buchanan


To add to insin's answer, ids do have practical uses, but styling is not one of them.

The two cases are fragment identifiers, and input/label pairing. In that case, you usually want to generate ids that are guaranteed to be globally unique (but consistent across renders). For that, use a mixin like unique-id-mixin.

like image 22
Brigand Avatar answered Sep 22 '22 23:09

Brigand