react native view conditional rending

Viewed 40

i'm new to react native. So i have this component:it will get a prop x from a parent component. is it possible to change the backgroundColor of only the Yollow View depending on x? or should i render the views separately instead of using map? any help will really be appreciated

     const [colors, setColors] = useState(["yellow", "blue", "green", "red"]);
     return ( <View style={{
        width: "100%",
        height: "100%",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        flexWrap: "wrap",}}>
      {colors.map((color, index) => (
        <View
          key={index}
          style={{height: "25%",backgroundColor:color,}}></View>))}
         </View>);};```

1 Answers
backgroundColor: color === 'yellow' ? (xCondition ? randomColor : color) : color

It is not recommended to nest ternary operations though so the better approach would be to have a function that returns the color like:

function getColor(x, currentColor){
  if(currentColor === 'yellow') {
    return xCondition ? randomColor : currentColor
  }
  return currentColor
}

and

backgroundColor: getColor(x, currentColor)
Related