'How to show/hide a button in ReactNative?
I am trying to code an alarm app and I would like to hide a button if the alarm is enabled and show it if the alarm is disabled so the user can enable the alarm again. Disabling and enabling the alarm happens on the alarm screen, however the home screen shows if the alarm has been enabled/disabled in the alarm screen as well. The home screen is where the button to switch the alarm back on is located.
I get the state of the alarm through redux toolkit in switch.js:
import { createSlice } from '@reduxjs/toolkit';
const initialStateValue = {
active: true
}
const switchSlice = createSlice({
name: 'alarm',
initialState: initialStateValue,
reducers: {
toggleOn: (state = initialStateValue) => {
state.active = true;
},
toggleOff: (state = initialStateValue) => {
state.active = false;
},
}
});
export const {toggleOn, toggleOff} = switchSlice.actions;
export default switchSlice.reducer;
In the main screen I have this so far:
import { useDispatch, useSelector } from 'react-redux';
import { toggleOn, toggleOff } from '../components/switch';
function Home({navigation}) {
const alarmOff = require('../images/Alarm_off.png');
const alarmDisabled = require('../images/Alarm_off_disabled.png');
const switchValue = useSelector((state) => state.alarm.active);
const dispatch = useDispatch();
function activateAlarmHandler() {
if (switchValue == true) {
dispatch(toggleOff());
} else {
dispatch(toggleOn());
}
}
return (
<View style={globalStyles.containerMainHome}>
<ImageBackground
source={switchValue ? alarmOff : alarmDisabled}
>
<Pressable
style={({pressed}) => pressed
? [globalStyles.button, styles.pressed]
: globalStyles.button}
onPress={activateAlarmHandler}
>
<Text style={globalStyles.textButton}>Activate Alarm</Text>
</Pressable>
</ImageBackground>
</View>
);
}
The function 'activateAlarmHandler' works really well, I can activate and deactivate the alarm from the home screen and the alarm screen gets it. But how do I hide the Button (Preassable) if switchValue is true?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
