Setting a classname attribute is a common way to style elements in React. JSX allows you to embed JavaScript expressions, so you can set className to a dynamic value and style elements conditionally.

Include variable in className string

className attribute needs to be set to a string.

Fortunately, template literals allow you to embed dynamic expressions inside a string.

Let’s look at an example:

function App() {

  const size = "large"
  const type = "danger"
  return (
    <h1 className={`${size} main ${type}`}>

       Hello World
    </h1>
  );
}

Template literals are a JavaScript feature. To use them in JSX, you need to wrap them in curly braces.

Beginning and end of template literals are marked by backticks (“).

You need to use dollar sign $ followed by another pair of curly braces to embed dynamic expressions in template literals.

In the above example, size and type variables will be replaced by their respecitve string values.

Set className to a variable

className attribute works same as class attribute in HTML. Except you can set it to dynamic values as well as a static string.

For now, let’s see how to set className to a variable in React.

<h1 className={size}>Hello, World</h1>
...
const size = "large"

Curly braces allow you to include dynamic expressions in JSX. In this case, we use them to set className to a variable, named size.

className string with a variable

Sometimes className string value is part static, part dynamic.

You can use template literals to add variable in classname value in React.

Template literals allow you to embed dynamic expressions inside the string. Some part of the string will be static. In other words, it will always be the same. Some part of the string will be dynamic (its value will change depending on the variable).

Normal strings start and end with single or double quotes.

const text = "normal string"

Template literals’ beginning and end is marked by backticks.

const text = `dynamic string`

In this specific example, neither of the strings include a variable.

You can, however, use dollar sign and curly braces to add dynamic parts to the string.

`${size} main`

Everything between curly braces will be interpreted as a JavaScript expression. In this case, the size variable.

The part outside the curly braces will be interpreted as normal string.

className with multiple variables in React

Template literals can include as many JavaScript expressions as you want.

You can also choose position and order of variables in a className value.

For example, here’s a template string where first className value is a variable, second is a normal string, followed by a variable again.

`${size} main ${type}`

Current value of the string will be determined by values of size and type variables.

UX