JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Using multiple class names in React

Author:JIYIK Last Updated:2025/03/17 Views:

When developing complex applications, it's not uncommon to have HTML elements with multiple classes. If you're familiar with HTML and CSS, you're probably familiar with the syntax for setting multiple classes. In this article, we'll look at a number of different ways to do this in React.

Most React developers use JSX, a special syntax for writing simple component definitions. Its syntax is very similar to HTML, which is why most React developers prefer it. There are some essential differences regarding setting classes.

In HTML, you may be used to classsetting classes using the Attribute. Since React components can be defined as instances of classes, Class is a reserved word. Therefore, developers must use classNamethe Attribute instead.

In JSX, classNameattributes must be set equal to a string. A simple definition containing multiple classes looks like this:

<h1 className="classOne classTwo">Hi! Try edit me</h1>

Alternatively, you can classNameset the property equal to a JavaScript expression that returns a string. To ensure that the expression is correctly interpreted as JavaScript code, you must enclose them between curly braces. Let's look at an example:

const color = "white"
<h1 className={"classOne " + color }>Hi! Try edit me</h1>;

In this example, we added a regular string and a string value contained in a variable. Once the expression is evaluated, our classNameproperty will be equal to 'classOne white'the string.

We can make the expression more readable by +replacing the operator with .concat()the method, which concatenates two strings into one.

const color="white"    
h1 className={"classOne ".concat(color)}>Hi! Try edit me</h1>

This standard JavaScript method can be used to convert an array of string values ​​into multiple classNamevalues. Since it is a JavaScript method, we need to put the entire expression between curly braces in JSX.

By default, combined string values ​​will be separated by commas. However, to produce a valid classNamelist of values, we need to separate them with a single space. Fortunately, we can ' 'specify the separator by passing a single space string as an argument to the method. Here is an example:

class App extends Component {
  render() {
    const arr = ["bold", "primary", "lead"]
    return (<div><p className={arr.join(" ")}>Hi! Try edit me</p></div>)
  }
}

In the file on playcodestyles.css , we define three classes:

.lead {
  font-size: 40px;
}
.bold {
  font-weight: bold;
}
.primary {
  color: white
}

After executing the code inside the curly braces, you can see that all three classes are applied.

You can also view the source code to verify that these classes are applied to <p>the element.

<div id="app">
    <div class="container black">
        <p class="bold primary lead">Hi! Try edit me</p>
    </div>
</div>

In ES6, we can use array destructuring syntax to create a nice custom function that returns a formatted string that we can use as classNamea value.

Let's look at the code:

class App extends Component {
  render() {
    const classNameGenerator = (...classes)=>{
      return classes.join(" ")
    }
    return (<div className={classNameGenerator("container")}></div>)
  }
}

This function treats its arguments as array items and then .join()returns classNamea formatted list of values ​​using the method.

When using this function, you can pass as many string values ​​as you want.

Conditionally applying classNamea value is useful for changing the appearance of an element based on user input. For example, if your app has dark and light themes, its background should also switch from light to dark. Here is a code example:

const lightBackground = !this.state.darkTheme ? "white" : "black"
<div className={classNameGenerator("container") + " " + lightBackground }></div>

lightBackgroundThe variable darkThemeis assigned to one of two strings depending on the value of the state property. In addition to calling classNameGenerator("")the function, we also use +the operator to include conditional values ​​for the variable.

To better demonstrate, our playcode application contains a button that toggles the value darkThemeof a property boolean.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:85 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial