I am creating a todo app in which a dialog is to be shown when button is clicked and when the button cancel is clicked it need to be dismissed. I have two components which are:
AddTodo.js
import { Modal, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { GetInfoDialog } from "./GetInfoDialog";
import { React, useState } from "react";
function useChange() {
const [state, setState] = useState(false);
function change(value) {
setState(value);
console.log("state: " + value);
}
return { state, change };
}
function AddTodo() {
const { state, change } = useChange();
return (
<View style={styles.container}>
<Modal
animationType="slide"
transparent={true}
visible={state}
style={styles.itemsContainer}
>
<GetInfoDialog />
</Modal>
<TouchableOpacity
style={styles.btn}
onPress={() => {
change(true);
// console.log("btn click: " + clicked);
}}
>
<Text style={styles.text}>Add New</Text>
</TouchableOpacity>
</View>
);
}
and
GetDialogInfo.js
import react, { useState } from "react";
import { useChange } from "./AddTodo";
import {
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from "react-native";
function GetInfoDialog() {
const { state, change } = useChange();
return (
<View style={styles.container}>
<Text style={styles.headerText}>Add Todo</Text>
<TextInput style={styles.input} />
<View style={styles.btnContainer}>
<TouchableOpacity style={styles.btn}>
<Text style={styles.text}>Add</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.btn}
onPress={() => {
change(false);
}}
>
<Text style={styles.text}>Cancel</Text>
</TouchableOpacity>
</View>
</View>
);
}
I am try to change the state using the change function but the state is not getting changed.
3
Answers
The useChange function you have written is working as a custom hook. It doesn’t connect the two components. Can I know what is your requirement?
You are trying to share
state
andchange
in the different components:AddTodo
andGetInfoDialog
byconst { state, change } = useChange();
But it’s not possible in your app because you actullay created 2
state
s andchange
s through your custom hook.To share it, you need to define them once and pass them as props into
GetInfoDialog
.e.g.
And pass
state
andchange
created in yourAddTodo
.