Braces in Attributes
Part of the Fundamentals section of Coddy's React journey — lesson 8 of 42.
Curly braces work in attributes too. Swap the quotes for braces and the attribute value comes from JavaScript:
const level = 'warning';
return <p className={level}>Check this!</p>;Now the paragraph's class is whatever the variable holds: change level to 'error' and the class follows. This is how React apps switch styles based on data.
Note the syntax carefully: className={level}, no quotes around the braces. className="{level}" (with quotes) would set the class to the literal text {level}.
Challenge
EasyThe alert paragraph should get its CSS class from the level variable.
- Set the paragraph's
classNameto the value oflevelusing curly braces (its class must end up aswarning). - Don't type the word warning in the attribute. Use the variable.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="main.jsx"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2JSX Expressions
Curly BracesMath in BracesBraces in AttributesCalling Functions in JSXRecap: JSX Expressions5State & Events
What Is State?Click CounterCount in StepsToggle with StateIndependent StateRecap: State & Events8Project: Profile Card
Step 1: Card StructureStep 2: Card with PropsStep 3: Like ButtonStep 4: Follow Toggle