Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally apply CSS classes in React JS

I've been musing on how best to conditionally apply a CSS class in React JS. I've seen some answers banding around but there aren't many out there or they're just not as elaborative as I'd like.

like image 947
Mr. Benedict Avatar asked Sep 01 '16 21:09

Mr. Benedict


People also ask

How do I apply a CSS condition in React?

Create a new react application or open existing react app. Declare two different CSS style objects named as objectStyle and objectStyleValid with below attributes (in Code). Next we will declare a const variable named “isValid”. Based on its value (true/false) we will try to change the CSS style.

How import conditional CSS React?

You can use require('file. css') or import('file. css') syntax instead -- that will allow you to use it inside of a conditional. You might need babel-plugin-syntax-dynamic-import for the import() syntax.


2 Answers

You can simply condition class to state, like this:

<div className={ this.state.exampleIsTruthy ? 'yourClass' : '' }>   text </div> 

or if you want to switch classes based on a state like this:

<div className={ this.state.exampleTrueOrFalse ? 'shown' : 'hidden' }>   text </div> 
like image 128
Adam Orłowski Avatar answered Oct 03 '22 20:10

Adam Orłowski


The React documentation on manipulating class names suggests the classnames NPM package.

The docs for the package are great.

The following snippet is straight from the package README: Usage section

classNames('foo', 'bar');                 // => 'foo bar' classNames('foo', { bar: true });         // => 'foo bar' classNames({ 'foo-bar': true });          // => 'foo-bar' classNames({ 'foo-bar': false });         // => '' classNames({ foo: true }, { bar: true }); // => 'foo bar' classNames({ foo: false, bar: true });    // => 'bar'  // lots of arguments of various types classNames('foo', { bar: true, duck: false }, 'baz', { quux: true });  // => 'foo bar baz quux'  // other falsy values are just ignored classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, '');  // => 'bar 1' 
like image 24
Ross Allen Avatar answered Oct 03 '22 22:10

Ross Allen