Author avatar

Gaurav Singhal

How to Assign a Class to an Element

Gaurav Singhal

  • Jun 9, 2020
  • 7 Min read
  • 139 Views
  • Jun 9, 2020
  • 7 Min read
  • 139 Views
Web Development
Front End Web Development
Client-side Framework
React

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
jsx

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

1
2
3
4
5
6
style={{
       position: "absolute",
       top: "50%",
       left: "50%",
       transform: "translate(-50%,-50%)"
}}
jsx

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

1
2
3
4
5
6
.myDiv {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
css

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
jsx

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.

1
2
3
.tableRoot {
  border: 2px solid purple
}
css

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

1
2
3
4
5
6
constructor() {
    super();
    this.state = {
      isTableVisible: true
    };
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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>
    );
}
jsx

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.

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

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.

1
<table className="classname1 classname2 classname3">
jsx

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.

1
npm install classname
powershell

After installing the package, use it as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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;
jsx

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

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

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!

1