Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React className with ternary operator add class 'null'

Tags:

reactjs

I'm trying to conditionally apply a class to my component using an expression like this:

.map(function(list, index) {
    <div className={"myClass " + (position === index ? 'active' : null)}>
}

But it keeps adding null as class, with an end result like this:

<div class="myClass active">...
<div class="myClass null">...

This is a simple example, with only 2 class names, so I could just replace null with the default class name. But in a more complex layout, I would need to duplicate the same name over and over again.

Is there a better approach to solve this problem?

like image 923
celsomtrindade Avatar asked Apr 10 '17 12:04

celsomtrindade


1 Answers

You could use an empty string '' instead of null like:

.map(function(list, index) {
    <div className={"myClass " + (position === index ? 'active' : '')}>
}

Also map should return a value:

 .map(function(list, index) {
     return <div className={"myClass " + (position === index ? 'active' : '')}>;
 }
like image 103
Hamza Baig Avatar answered Sep 28 '22 05:09

Hamza Baig