I have 2 user text inputs called Search Location and Coordinates. I'm trying to use a checkbox when selected allows search location to be edited and the coordinates input be disabled and vice versa when the checkbox is not selected.
When i first run the code, i can edit Search Location and Coordinates is disabled. When i select the checkbox the text input works fine, Search Location is disabled and Coordinates is editable. However, when i try to unselect the checkbox, Search Location is still disabled and Coordinates can still be edited.
I have tried using useEffect but im not too familiar with this nor do i know if this is the correct approach. I am using react hook forms for user inputs and i use react native elements for checkboxes.
Code:
export default function UserInput({ navigation }) {
const { handleSubmit, control } = useForm();
const [checkbox, setCheck] = useState(false);
const [edit1, setEdit1] = useState(true);
const [edit2, setEdit2] = useState(false);
const onSelect = () => {
if (!checkbox) {
setEdit1(false);
setEdit2(true);
}
setCheck(!checkbox);
};
return (
<View style={styles.formContainer}>
<Text style={styles.text}>Distance(km)</Text>
<Controller
name="distance"
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, value } }) => (
<TextInput
placeholder="Enter your Distance"
style={styles.input}
onChangeText={onChange}
value={value}
/>
)}
/>
<Text style={styles.text}>Search Location</Text>
<Controller
name="searchLocation"
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, value } }) => (
<TextInput
placeholder="Enter your Coordinates"
style={styles.input}
onChangeText={onChange}
value={value}
editable={edit1}
/>
)}
/>
<CheckBox
center
title="Current Location"
checked={checkbox}
onPress={onSelect}
/>
<Text style={styles.text}>Coordinates</Text>
<Controller
name="coordinates"
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, value } }) => (
<TextInput
placeholder="Enter your Coordinates"
style={styles.input}
onChangeText={onChange}
value={value}
editable={edit2}
/>
)}
/>
</View>
);
}
CodePudding user response:
Try this one
const onSelect = () => {
if (!checkbox) {
setEdit1(false);
setEdit2(true);
} else {
setEdit1(true);
setEdit2(false);
}
setCheck(!checkbox);
};