Search code examples
javascriptreactjsreact-nativestyled-components

How to change a background color based on a variable?


So I'm calling PokeAPI to create a Pokedex, and I want to make it so when the first type of the pokemon is "grass", for example, the background is green, when it's "fire", the background is red, etc.

I've declared it as green initially, because the first 3 Pokémons (Bulbasaur, Ivysaur and Venusaur) are grass type, and I was able to create a condition to change it to red when the type is fire. I don't know though how to create more conditions inside the same style for the same parameter (background).

As of now, this part of the code looks like this and it's working perfectly: ( is a component from styled-components)

<Background style = {{background: typea === "fire" ? "#ff726f" : ""}}>

I just want to add more conditions like:

if typea === "fire" ? "red": ""
if typea === "bug" ? "yellow" : ""
if typea === "poison" ? "purple" : ""

etc.

All the ways I've tried to declare that have resulted in an error.


Solution

  • I would just use a map:

    const backgrounds = {
        fire: 'red',
        bug: 'yellow',
        poison: 'purple',
    }
    const defaultBackground = 'white';
    
    <Background style = {{background: backgrounds[typea] || defaultBackground }}>