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:
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.
1exportdefaultfunctionAlertBox(){
2const alertStyles ={
3backgroundColor:'#fee2e2',// camelCase instead of background-color
4color:'#991b1b',
5padding:'16px',
6borderRadius:'8px',
7fontSize:'14px'// camelCase instead of font-size
8};
9
10return(
11<divstyle={alertStyles}>
12<strong>Attention:</strong> Your lab environment resets in10 minutes.
13</div>
14);
15}
16
17// Or passed directly inline:
18<divstyle={{color:'blue',marginTop:'20px'}}>
19 Direct Inline Styling
20</div>
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:
1// ❌ Syntax Error in JSX: Unterminated JSX contents
2<inputtype="text">
3<imgsrc="logo.png">
4<hr>
5
6// ✅ Valid JSX: Properly self-closing
7<inputtype="text"/>
8<imgsrc="logo.png"alt="Company Logo"/>
9<hr/>
10
11// ✅ Custom React components with no children should also self-close
12<Sidebarnavigation={navLinks}/>
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
Why does inline styling in JSX often look like style={{ color: 'red' }}?
Question 2
How must the CSS property background-color be written when passing inline styles to a React element?
Question 3
Which of the following elements is syntactically INVALID in JSX?
Question 4
How do you pass a boolean true value to an attribute named isActive in JSX?
Question 5
What is the correct way to specify multiple dynamic classes conditionally using standard JavaScript template literals?
Next Lesson
React Fragments and Returning Clean Markup
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.