How can I close my Modal which is inside another custom component?
My modal is in another component. I have a problem passing a state to the parent component. You can see the parent and child component below.
Parent Component:
const ViewNote = ({route, navigation}) => {
const [visible, setVisible] = useState(false);
function visibility(cases) {
setVisible(cases);
console.log(cases);
}
return (
<View style={styles.noteContainer}>
{/* MODAL */}
<FancyAlert visible={visible} />
<View style={styles.deleteContainer}>
<Pressable android_ripple={{color: '#d9d9d9'}} onPress={() => setVisible(true)}>
<MaterialIcons style={styles.icon} name='delete' size={40}/>
</Pressable>
</View>
</View>
)
}
export default ViewNote
Child Component:
const FancyAlert = ({visible}) => {
const [showAlert, setShowAlert] = useState(false);
return (
<Modal transparent visible={visible}>
<View style={styles.modalContainer}>
<View style={styles.dialogContainer}>
<Text style={[styles.text, {fontSize: 16}]}>Are you sure you want to delete this note?</Text>
<View style={styles.buttonContainer}>
<Pressable style={styles.cancel} android_ripple={{color: '#d9d9d9'}} onPress={() => setVisible(false)}>
<Text style={[styles.text, {fontFamily: 'SofiaProBold'}]}>Cancel</Text>
</Pressable>
</View>
</View>
</View>
</Modal>
)
}
export default FancyAlert
3
Answers
Move state to parent component. And pass onClose function.
You can pass also setVisible to the child component, and invoke it with the value you want.
and use it as:
Child Component:
You should simply pass the "visibility" function as prop for FancyAlert.
Your code should be something like that:
And than the FencyAlert component should be:
This should do the job