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