JSX Attributes, ClassName, and Self-Closing Tags
JSX Attributes, ClassName, and Self-Closing Tags
1. Attributes in JSX
Attributes in JSX allow you to configure elements and components with data, behavior, and styling. While many attributes resemble their HTML counterparts, JSX attributes follow standard JavaScript DOM properties and strict naming conventions.
Passing String Literals vs Expressions
- For static strings, pass the value enclosed in quotes:
- For numbers, booleans, arrays, functions, or variables, wrap them in curly braces:
2. The className Attribute
In standard HTML, styles are applied using the class attribute (<div class="card">). In JSX, you must write className:
3. Passing Inline Styles: The Double Curly Braces {{}}
A common stumbling block is inline styling in JSX. In HTML, styles are passed as semicolon-separated strings (style="color: red; font-size: 16px;"). In JSX, the style attribute expects a JavaScript object.
This creates the syntax pattern style={{ ... }}:
- The outer braces
{ }indicate a dynamic JavaScript expression. - The inner braces
{ }represent a JavaScript object literal.
Note: CSS property names that feature hyphens (like font-size, background-color, margin-top) are converted to camelCase in JSX (fontSize, backgroundColor, marginTop).
4. Self-Closing Tags
In standard HTML5, several elements are categorized as "void elements" (elements that cannot contain child nodes or closing tags), such as:
<img><input><br><hr><meta>
In HTML, writing <img> without a slash is valid. In JSX, this is a syntax error. Any element that has no children must be explicitly self-closed using a trailing forward slash:
Practice Quiz
style={{ color: 'red' }}?background-color be written when passing inline styles to a React element?true value to an attribute named isActive in JSX?React Fragments and Returning Clean Markup
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Embedding JavaScript Expressions in JSX | React Fragments and Returning Clean Markup |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.