Harshan
Harshan

Reputation: 37

How to simplify multiple if else conditions in JavaScript - React JS

how to reduce this condition logic in a simpler way. if the status values increase the conditions go on and on, please help to write a clean code

const getColor = status => {
    if (status === 'positive') {
      return { backgroundColor: 'red' }
    } else if (status === 'negative') {
      return { backgroundColor: 'orange' }
    } else if (status === 'neutral') {
      return { backgroundColor: 'blue' }
    }else if (status === 'none') {
      return { backgroundColor: 'white' }
    }else if (status === 'all') {
      return { backgroundColor: 'black' }
    }
  }

     <p style={getColor(result.sentiment_label)}>test</p>

Upvotes: 1

Views: 555

Answers (4)

wscourge
wscourge

Reputation: 11281

Use object instead:

const COLORS = {
  positive: "red",
  negative: "orange",
  neutrla: "blue",
  none: "white",
  all: "black",
}

<p style={{ backgroundColor: COLORS[result.sentiment_label] }}>
  test
</p>

Upvotes: 1

nikoswsn
nikoswsn

Reputation: 192

One way could be the following:

const getColor = status => {
        if (status === 'positive') return { backgroundColor: 'red' }
        if (status === 'negative') return { backgroundColor: 'orange'}
        if (status === 'neutral') return { backgroundColor: 'blue' }
        if (status === 'none') return { backgroundColor: 'white' }
        if (status === 'all') return { backgroundColor: 'black' }
        return null
      }

Considering that you return inside the if statement next conditions won't run, thus you don't need else if. Furthermore you can remove curly brackets considering that you only have one command per if statement

Upvotes: 0

Raziel
Raziel

Reputation: 1566

switch statement maybe? Itll certainly read much nicer:

    const getColor = status => {
      switch(status) {
        case 'positive':
          return 'red';
        break;
        case ''negative:
          return 'orange'
        break;
        case ''neutral:
          return 'blue'
        break;
       case ''none:
          return 'white'
        break;
      default:
        return 'black'
     }
    }
    
  <p style={{backgroundColor: getColor(result.sentiment_label) }}>test</p>

Upvotes: 0

Franck Grall
Franck Grall

Reputation: 41

For your usecase, you can use switch :

switch (status) {
  case 'positive':
    return { backgroundColor: 'red' }
  case 'negative':
    return { backgroundColor: 'orange' }
  ...
  default:
    return { backgroundColor: 'black' }
}

Another solution, which is shorter (but can be harder to read) can be :

const statusBgColorMap = {
  positive: 'red',
  negative: 'orange',
  ...
}

return { backgroundColor: statusBgColorMap[status] || 'defaultcolor' }

Upvotes: 4

Related Questions