Home > Software design >  optimize style condition for better pattern
optimize style condition for better pattern

Time:02-04

hi I want to change my CSS condition in JSX from this condition:

   style={{
          background:
            (input.categoryName[0] === "A" ? "#FF6F33" : null) ||
            (input.categoryName[0] === "B" ? "#2C828f" : null) ||
            (input.categoryName[0] === "C" ? "#C048EE" : null) ||
            (input.categoryName[0] === "E" ? "#01D584" : null) ||
            (input.categoryName[0] === "F" ? "#FF47BE" : null) ||
            (input.categoryName[0] === "G" ? "#F96693" : null) ||
            (input.categoryName[0] === "H" ? "#549EF0" : null) ||
            (input.categoryName[0] === "I" ? "#FEA544" : null),
        }}

to something like this :

  (input.categoryName[0] === "A" ? "#FF6F33" :
                         === "B" ? "#2C828f" : 
                         === "C" ? "#C048EE" :
                         === "E" ? "#01D584" :
                         === "F" ? "#FF47BE" :
                         === "G" ? "#F96693" :
                         === "H" ? "#549EF0" :
                         === "I" ? "#FEA544" : null),

any suggestion?

CodePudding user response:

An object to map key-value pairs may simplify your code.

const background = {
  'default': '#ff0000',
  'a': '#FF6F33',
  'b': '#2C828f',
  // etc.
}

const category = input.categoryName[0].toLowerCase() ?? 'default'

style={{
  background: (background[category])
}}
  •  Tags:  
  • Related