8

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?

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

My first thought was: What about performance, surely using id would be faster? Found some info here: stackoverflow.com/a/31027148/945875 In the end, id lookup is faster when used as the "key" selector but the gain is so minimal (1ms for 1000 rules in a performance test) that it doesn't matter (and you can avoid some tricky inheritance issues).
1

ID's are for single use (in React and in general) or one-time instances.

classNames are for multiple usage (in React and in general) or for many-time instances - the same way that classes are used in traditional CSS.

Comments

0

First of all, ids are used with React, and they don't necessarily prevent re-use. For instance, if you'd want to use a element then you'd have to give it an ID (so it can be referenced from the "list" attribute of its tag). In that case, I usually auto-generate an ID using a counter variable. Hence, IDs and re-use don't have to rule each other out.

To answer your question, the className attribute is used instead and works just like the class attribute. The "react/addons" module provides a utility for easily creating className values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.