-1

The title might be confusing, so here is an example....

for (var i = 0; i < this.state.list.length; i++) {
    <td className={'blah_'+this.state.list[i].id}></td>
}

This results in <td class="blah_1">, but what if you need to put a hard-coded class name along with class="blah_1"?

<td className={'blah_'+this.state.id, 'another-class'}></td>

This ended up <td class="another-class">.

<td className={'blah_'+this.state.id}  className="another-class></td>

So did this one.

So, my goal is to get <td class="blah_1 another-class">, meaning that one is determined dynamically and the other is hard-coded. Sorry this question sounds too basic, but I'm new to react and can't find the answer in the official documentation.

I'd appreciate if you would give any insight.

Hiroki
  • 2,573
  • 9
  • 40
  • 65
  • 2
    `className={"another-class blah_" + this.state.id}` or even better with template literals: `className={\`another-class blah_${this.state.id}\`}` – Andrew Li Jan 18 '17 at 22:41
  • 1
    And if you're curious, the reason why `className={'blah_'+this.state.id, 'another-class}` evaluates to `another-class` is because the comma operator always evaluates to the last value. See [here](http://stackoverflow.com/q/3561043/5647260). – Andrew Li Jan 18 '17 at 23:07

3 Answers3

2

With template strings.

<td className={`blah_${this.state.id} another-class`}></td>
D. Walsh
  • 1,803
  • 1
  • 15
  • 19
1

While there may be several fancy ways of doing it, given the clear confusion about what is happening in your question, it is definitely worth noting that this is just javascript outputting a string to className which becomes class on the html element, so just add the name of another one on like you would in html:

<td className={'blah_'+this.state.list[i].id + ' another-class'}></td>
-2

This is amazing for that https://github.com/JedWatson/classnames and we use it on all our components with mixes of dynamic and static classes

but before that I would use functions like:

getClass() {
 const class = 'base-class';

 if (this.state.id) {
   class += ' blah_" + this.state.id  
 }

 return class
}

and then assign className to whatever getClass() returns

if you use the third party plugin you can do the following:

const classes = classnames('base-class', {
 ['blah_' += this.state.id] : true,
 disabled: this.props.disabled
}

and that will return the proper class string that you can apply to an elements className property. Either way works but as far as readability goes I prefer using the plugin.

finalfreq
  • 5,884
  • 1
  • 22
  • 27
  • downvoter can you explain? I'd also recommend classnames for this. – Balázs Édes Jan 18 '17 at 22:42
  • 2
    The answer before was just a link, so that was VLQ. Anyways, why the extra method when template literals can do just this, or just concatenating? Why the extra library? – Andrew Li Jan 18 '17 at 22:43
  • @AndrewLi This just reminds me of 'how do i add two numbers in javascript' lol –  Jan 18 '17 at 23:02