CodeBlanks Logo Icon CodeBlanks

Attributes and className

Learn how attributes are written in JSX and that className replaces class.

Attributes and className

In JSX you write HTML attributes, but some get different names. The most common: className instead of class, htmlFor instead of for.

Attribute names use camelCase: tabIndex, readOnly, maxLength. Values are strings in double quotes or expressions in curly braces: <img src="logo.png" /> or <img src={logo} />.

For boolean attributes prefer disabled={true} over the bare disabled. JSX accepts both, but being explicit is clearer.

camelCase attributes

In JSX attributes use camelCase; the dashed names from HTML become one piece. Use maxLength instead of maxlength, tabIndex instead of tabindex.

Event attributes are camelCase too: not onclick but onClick, not onchange but onChange. You pass them a function, not a string.

The style attribute is special: it takes an object with camelCase keys. style={{ color: 'red' }} is right, style="color:red" is wrong.

Practice Write a card with className

Complete the skeleton. Write a component called Card that returns <div className="card"> with <p>Welcome</p> inside, and export it.

Starter code

App.jsx
// Write the Card component here

Sample solution

App.jsx
function Card() {
  return <div className="card"><p>Welcome</p></div>;
}

export default Card;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What replaces class?

  • classes
  • cssClass
  • className Correct answer
  • class

Explanation: class is replaced by className because class is a reserved word in JavaScript.

2 Using htmlFor

Question
<label ____="email">Email</label>
Answer
<label htmlFor="email">Email</label>

Explanation: for is replaced by htmlFor.

3 Match the attributes

Term Meaning
className class
htmlFor for
onClick onclick
maxLength maxlength

All lessons in Beginner