Home > Mobile >  how to change button background color depend on his value using useStatee hook withount it changing
how to change button background color depend on his value using useStatee hook withount it changing

Time:06-10

solution: i changed the hook to:

const [flagC, setFlagC] = useState(props.cars[i].state===on? 'green' : 'red');

and the function to:

const onOff=()=>{debugger;
        if(props.cars[i].state===on){
          setFlagC('red');
          props.cars[i].state=off;
        }
        else if(props.cars[i].state===off){
          setFlagC('green');
          props.cars[i].state=on;
        }
    }

i have an array in my app.js thats holds cars and each car has state on/off:

let cars=[{name: 'mazda', state: off},{name:'toyota', state:off},{name: 'volvo', state:off}];

now i have component that recives this array and display each car in diffrent button (using map at app.js):

{cars.map((val,i)=>{
  return <ComponentName  carName={val.name} index={i}/>
})}

i created inside the component a hook thats hold red color: const[flagC,setFlagC]=useState('red');

and a function thats supposed to check what is the car state and if its off set the button background color red and if its on set is green set the state as "on". its changes the color of the car but as i pass to another page on the app it set it back to red but the state remains on. what i need to change?

heres the function:

const[flagC,setFlagC]=useState('red');

    const onOff=()=>{debugger;
        if(props.cars[i].state===on){
          props.cars[i].state=off;
          setFlagC('red');
        }
        if(props.cars[i].state===off){
          props.cars[i].state=on;
          setFlagC('green');
        }
    }

the value get the correct car by index and the hook is the style of the button the butoon has onClick.

 <button style={{backgroundColor: flagC}} onClick={onOff}>{props.carName}</button>

CodePudding user response:

You are not updating your color state when component loads. I suggest the following:

const [color, setColor] = useState(props.cars[i].state===on ? 'green' : 'red')

Explaining: Every time the component mounts it uses the initial value for the state until you update the state depending on the incoming data (props or not). If data comes as props then you can define your state to have the initial value as soon as you call useState, if data comes from a function call or an async or a redux change then you must use useEffect to update your state.

Since it seems that your data comes as props the you can write useState(props match condiction ? valueOne: valueTwo)

  • Related