Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change classes to an element with react

Tags:

reactjs

I'd like to do something like Angular does with ng-class. I'm using react-tabs library (https://github.com/mzabriskie/react-tabs) and now I want to be able to change the background of the selected tab. The library comes with a default effect for the selected tab but I want personalize it.

like image 327
George Cscnt Avatar asked Sep 01 '15 20:09

George Cscnt


People also ask

How do you apply dynamic classes to an element in React?

Use Native JavaScript to Set Dynamic className Values in React. The simplest way to add dynamic className values is to combine curly braces and set the className attributes equal to the state variables. This is a fairly simple feature available in all versions of JavaScript.

How do you manipulate a className in React?

Class Name Manipulation Edit on GitHubclassSet() is a neat utility for easily manipulating the DOM class string. When using classSet() , pass an object with keys of the CSS class names you might or might not need. Truthy values will result in the key being a part of the resulting string.


3 Answers

if you're using an es6 transpiler you can use template strings and a ternary:

className={`base-class ${this.props.isActive? 'is-active' : ''}`}
like image 58
Benjamin David Avatar answered Oct 12 '22 01:10

Benjamin David


This works:

<div className={this.props.canChange ? "change-button" : "change-button gray-out"}>
blah
</div>

Basically classname is a property of the node.

like image 3
Ada P Avatar answered Oct 12 '22 02:10

Ada P


Just wrap your <Tabs> element with an element of your own <div className="my-tabs"> and go from there! You can use the aria-selected to style the selected state.

like image 1
Eelke Avatar answered Oct 12 '22 01:10

Eelke