Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Assign a Class to an Element

Jun 9, 2020 • 7 Minute Read

Introduction

React creates intuitive user interfaces by following component-based architecture, in which each component consists of various HTML elements that require styling logic. There are various options available to style the component, and your choice ultimately depends on what is the most feasible and suitable styling for your situation.

In this guide, you will learn different ways of styling components, such as using inline style, using the class name, and conditional class name assignment.

Assign Inline Styles

Inline style assignment is one of the approaches used to style elements. It uses the name of the style followed by its values.

To provide the inline style to the elements, use the added property along with the element called style.

A complete example of inline styling is below.

      import React, { Component } from "react";

class InlineStyle extends Component {
  render() {
    return (
      <div>
        <span>Apply inline style to element</span>
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%,-50%)"
          }}
        >
          <span>This is a centered DIV using CSS inline style</span>
        </div>
      </div>
    );
  }
}

export default InlineStyle;
    

In the above example, notice that there is one added property called style, used like this.

      style={{
       position: "absolute",
       top: "50%",
       left: "50%",
       transform: "translate(-50%,-50%)"
}}
    

It can apply the various stylesheet rules, and it is also possible to have multiple stylesheet rules using comma separator styles.

Assign a Class Name

As you create any new web app, you can choose a stylesheet configuration such as CSS, SCSS, or SASS. Assign the styles at the time of implementing the chosen stylesheet.

Another way of assigning the class name to the various HTML elements is by using the class name.

Below is a simple example that shows how to assign the class name directly to the element.

The first step is to add the class to the CSS stylesheet file, as shown below.

Style.css

      .myDiv {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
    

After creating the stylesheet file, the next step is to create the element and assign the class name that you created before.

      import React, { Component } from "react";
import "./style.css";

class AssignClass extends Component {
  render() {
    return (
      <div>
        <span>Apply inline style to element</span>
        <div className="myDiv">
          <span>This is a centered DIV by applying class name</span>
        </div>
      </div>
    );
  }
}

export default AssignClass;
    

As you can see, the class myDiv is created in the stylesheet file, and the added property className is used to apply the styles to the <table> element.

This is how the class name can be assigned directly from the stylesheet, and this is the conventional approach to using class names.

Assign the Styles or Class Name Conditionally

So far in this guide. you have learned simple approaches to assigning styles, including using the inline style and using the stylesheet name. In many cases, however, you may need to assign the styles conditionally.

The styles or class name can be assigned conditionally by either using state & props, ternary operation, or any other conditional operator, such as && (and) or || (or).

Let’s create the styles class in the file style.css like this.

      .tableRoot {
  border: 2px solid purple
}
    

The next step is to create the state variable with the default value as stated below.

      constructor() {
    super();
    this.state = {
      isTableVisible: true
    };
}
    

In the above example, the state variable created is called isTableVisible with the true as a default value. The same variable can be used to assign the dynamic class name, as explained below.

      render() {
    return (
      <div>
        <span>Apply multiple class names</span>
        <div>
          <table className={this.state.isTableVisible ? 'tableRoot' : ''}>
            <tr>
              <td>Column 1</td>
              <td>Column 2</td>
            </tr>
            <tr>
              <td>Column 1</td>
              <td>Column 2</td>
            </tr>
          </table>
        </div>
      </div>
    );
}
    

In the render() function, there is one <table> element, but the provision is that the style is applied if the state variable is true, and if it is false, it works like this.

      <table className={this.state.isTableVisible ? 'tableRoot' : ''}>
    

This is one of the best approaches for when the class or styles need to be assigned dynamically based on a specific condition.

Assign Multiple Classes Using a Third-party Library

So far in this guide, you have learned how to assign styles or classes using conventional approaches, but when it comes to assigning multiple classes to an element, try the default approach below.

      <table className="classname1 classname2 classname3">
    

The same thing is also possible using the third-party package classnames, a widely used NPM package, to assign the class name.

Before using the package, install it using the below npm command.

      npm install classname
    

After installing the package, use it as shown below.

      import React, { Component } from "react";
import classNames from "classnames";
import "./style.css";

class ClassNames extends Component {
  render() {
    return (
      <div>
        <span>Apply multiple class names</span>
        <div>
          <table className={classNames("tableRoot", "tableAnotherRoot")}>
            <tr>
              <td>Column 1</td>
              <td>Column 2</td>
            </tr>
            <tr>
              <td>Column 1</td>
              <td>Column 2</td>
            </tr>
          </table>
        </div>
      </div>
    );
  }
}

export default ClassNames;
    

Here the primary focus is the line where the package classnames has been used.

      <table className={classNames("tableRoot", "tableAnotherRoot")}>
    

The import method classNames is used along with various class names as an argument. By using this method, you can assign multiple classnames, and the related styles can be applied to the desired element.

Conclusion

Styling an element is a standard operation in app development. You can choose different styling options, such as CSS or SCSS, and create related classes and use them along with the HTML elements.

In this guide, you learned all the usage scenarios to apply classnames and styles, including using inline style and class name third-party packages. I hope it will help you to style your app effortlessly. Thanks for reading!