'React Native - How to switch between several images depending on 2 states?
I am coding an alarm application right now and I can't seem to figure out how to display the desired image. There are two states:
- switchValue : the alarm is enabled(off) or disabled
- alarmValue : the alarm is on or off (triggered or not)
Right now only switchValue is displayed and it works depending on true/false. But how can I switch between images depending on switchValue AND alarmValue AND undefined if the alarm is not connected?
I get 'switchValue' and 'alarmValue' through redux toolkit.
Here's my code:
import { useDispatch, useSelector } from 'react-redux';
import { toggleOn, toggleOff } from '../components/switch';
import { alarmOn, alarmOff} from '../components/alarm';
function Home({navigation}) {
const imageAlarmOff = require('../images/Alarm_off.png'); // enabled but not triggered
const imageAlarmOn = require('../images/Alarm_on.png'); // enabled and triggered
const imageAlarmDisabled = require('../images/Alarm_off_disabled.png'); // disabled
const imageAlarmUndefined = require('../images/Alarm_undefined.png'); // not connected
const switchValue = useSelector((state) => state.switch.active);
const alarmValue = useSelector((state) => state.alarm.active);
const dispatch = useDispatch();
return (
<View style={globalStyles.containerBodyHome}>
<View style={globalStyles.containerMainHome}>
<ImageBackground
style={globalStyles.imageHome}
source={switchValue ? imageAlarmOff : imageAlarmDisabled}
>
</ImageBackground>
</View>
</View>
);
}
export default Home;
Solution 1:[1]
If I understand correctly you would like to manage multiple images?
You can use switch statement and base on switchValue return appropriate image.
function Home({navigation}) {
const imageAlarmOff = require('../images/Alarm_off.png'); // enabled but not triggered
const imageAlarmOn = require('../images/Alarm_on.png'); // enabled and triggered
const imageAlarmDisabled = require('../images/Alarm_off_disabled.png'); // disabled
const imageAlarmUndefined = require('../images/Alarm_undefined.png'); // not connected
const switchValue = useSelector((state) => state.switch.active);
const alarmValue = useSelector((state) => state.alarm.active);
const dispatch = useDispatch();
const handleImage = () => {
switch(switchValue) {
case true: {
if(alarmValue) return imageAlarmOn
return imageAlarmOff
}
case false: {
return imageAlarmDisabled
}
default: {
return imageAlarmUndefined
}}}
return (
<View style={globalStyles.containerBodyHome}>
<View style={globalStyles.containerMainHome}>
<ImageBackground
style={globalStyles.imageHome}
source={handleImage()}
>
</ImageBackground>
</View>
</View>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
