'Update snackbar state from parent component
I am trying to dismiss the snack bar after the user presses ok or after the duration. I tried passing an extra variable to the component and changing state but it does not work. Here is my code for the LogIn page that uses the snackbar component that renders only after a bad login request , its not the whole code:
const [error, setError] = React.useState(false);
const [username, setUsername] = React.useState('');
const [password, setPassword] = React.useState('');
const [visible, setVisible] = React.useState(false);
/* const form = createForm(data); */
return (
<View style={Style.container}>
{error && (
<View style={{width: '30%', height: '10%'}}>
<Snack_alert
message={'Wrong username or password!'}
textcolor={'white'}
btn_color={'white'}
snack_color={'red'}
dismiss={() => {
setVisible(false);
}}
/>
</View>
)}
and here is the child component:
export default function Snack_alert({
message,
textcolor,
btn_color,
snack_color,
dismiss
}) {
return (
<Snackbar
visible={true}
onDismiss={() => {
{
dismiss
}
}}
duration={2500}
theme={{
colors: {
surface: textcolor,
accent: btn_color,
onSurface: snack_color,
},
}}
//surface: text color , accent: undo color, onSurface: snackbar color
action={{
label: 'Ok',
onPress: () => {
{
dismiss
}
},
}}>
{message}
</Snackbar>
);
}
Also later in my code I update the setError to true so that I can render the snackbar , I am unsure if that causes any problems. Thanks in advance!
Solution 1:[1]
action={{ label: 'Ok', onPress: () => { { dismiss } }, }}
You don't call the dismiss-function. Either add parenthesis:
onPress: () => {
dismiss()
}
Or just pass the function directly:
onPress: dismiss
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 | Merlin Westphal |
