0 day streak
javascript / beginner
Snippet

Template Literals for Dynamic Classes

Template literals (using backticks ``) allow you to embed JavaScript expressions inside strings using ${}. This is very useful for creating dynamic CSS class names based on component props.

snippet.js
javascript
1
2
3
4
5
6
7
function Alert({ type, message }) {
return (
<div className={`alert alert-${type}`}>
{message}
</div>
);
}
react
Breakdown
1
className={`alert alert-${type}`}
Combines static strings with the value of the 'type' variable to form a full class name.