Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React conditional classnames using template strings and && operator

There have been many questions on StackOverflow relating to applying conditional classnames to React components; however, I have not seen a good answer for this particular situation:

I have a basic div that I want to conditionally apply the "is-required" class. Here is my approach:

<div className={`some-class ${isRequired && 'is-required'}`}>

The main issue here is that when isRequired is false, then my compiled HTML code ends up looking like this:

<div class='some-class false'>

Obviously, I could use a ternary operator like this so I can return an empty string instead:

<div className={`some-class ${isRequired ? 'is-required' : ''}`}>

But then in the compiled HTML code there is this extra random space included in the class, which won't cause any rendering issues, but I still don't like it:

<div class='some-class '>

Even still, I could remove the space after "someClass" and include it before "isRequired", but now it's harder to read and feels kind of clunky:

<div className={`some-class${isRequired ? ' is-required' : ''}`}>

I have heard of utilities such as classnames, but I am looking for a simple solution where I don't need any additional packages.

What is the recommended approach here?

like image 942
Drew Jex Avatar asked May 16 '18 17:05

Drew Jex


People also ask

Can you have two Classnames in React?

We can add a multiple class names to the react element conditionally; by using template literals, ternary operator.

How do you conditionally render a className in React?

The simplest approach is to use a ternary statement inside of a template literal. In this example, banner is always on the div , but active depends on the active prop. If you have a lot of class names that need to be conditional on the same element, it can get a little messy, but it still works.

How do I use Classnames in React?

In class-based components, the className attribute is used to set or return the value of an element's class attribute. Using this property, the user can change the class of an element to the desired class. Creating React Application And Installing Module: Step 1: Create a React application using the following command.


3 Answers

Actually, there are many ways to do that, here's one of them.

<div className={isRequired ? 'some-class is-required': 'some-class'}>

or you can return null

<div className={isRequired ? 'is-required' : null}>

In order, if you have several classes.

<div className={isRequired ? 'some-class is-required': isDisabled ? 'some-disabled-class' : 'some-class'}>

https://reactjs.org/docs/conditional-rendering.html

class App extends React.Component {

  constructor() {
    super();
    this.state = {
      isRequired: false
    };
}

  render() {
    return (
      <div className="App">
       <div className={this.state.isRequired ? 'is-required' : null}>Null</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
like image 54
Liam Avatar answered Oct 06 '22 10:10

Liam


You can use it if you don't want false value.

<div className={`some-class${isRequired && ' is-required' || ''}`}>
like image 45
Naim YÜREK Avatar answered Oct 06 '22 08:10

Naim YÜREK


Maybe you'll find this utility function helpful (it will be used as a tagged template):

const c = (strings = [], ...classes) => {
  let myClass = '';
  strings.forEach((s, i) => {
    myClass += s + (classes[i] || '');
  });

  return myClass.trim().replace('  ', ' ');
}

Now you can use it like this :

className={c`my-class ${this.props.done && 'done'} selected`}

or

className={c`some-class ${isRequired && 'is-required'} ${isDisabled && 'some-disabled-class'}`}
like image 4
Mohamed Ramrami Avatar answered Oct 06 '22 08:10

Mohamed Ramrami