Home > Net >  react native view conditional rending
react native view conditional rending

Time:11-09

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>);};```

CodePudding user response:

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)

CodePudding user response:

First, at the moment you apply logic inside the return, this piece gonna run any time the component should render (e.g. change in props either state)

import { Fragment, useMemo } from 'react'

const [colors, setColors] = useState(["yellow", "blue", "green", "red"]);
const getColors = useMemo(()=>{ <Fragment> {colors.map ... } </Fragment> } , [colors, props.x])
return ( 
      <View style={{
        width: "100%",
        height: "100%",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        flexWrap: "wrap",}}>
      {getColors}

Now, only changes at colors either props.x will make this piece run, and inside it, we can use memo to guarantee only yellow will change

import {memo} from 'react'

const MappedColor = memo(props =>
         <View
          key={props.index}
          style={{height: "25%",backgroundColor:props.color,}}></View>))}
         </View>,
         (props, nextProps) => nextProps.color != 'yellow' || props.x == nextProps.x)


colors.map((color,idx) => <MappedColor color={color} key={idx} x={props.x}/>)

CodePudding user response:

hi this code has problem , You have to give width and height to parent or View in map , You have to see what you want to do

{colors.map((color, index) => (
        <View
          key={index}
          style={{ height: 50 , backgroundColor: color , width: 50 }}
        ></View>
      ))}
  • Related