I have a custom Switch component that I want to use for my forms in react-native. The dilemma I have is how to obtain from this switch component its current state value.
I got a version of the switch working on this component:
/** @format */
// BASE
import React, { useState } from 'react';
import {
View,
Platform,
TouchableNativeFeedback,
TouchableOpacity,
Switch,
} from 'react-native';
// CONSTANTS
import Styles from '../../../../constants/Styles';
// TYPE
import SubtitleOne from '../../../type/SubtitleOne';
// COMPONENTS
import ListItem from '../ListItem/ListItem';
export default function SingleLineWithSwitch(props) {
const [isEnabled, setIsEnabled] = useState(props.value);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<ListItem onPress={() => toggleSwitch()}>
<View style={Styles.listSingleCointainer}>
<SubtitleOne style={Styles.listTitle}>{props.title}</SubtitleOne>
<View style={Styles.listSwitchView}>
<Switch
thumbColor={props.thumbColor}
trackColor={props.trackColor}
style={Styles.switchControl}
value={isEnabled}
onValueChange={toggleSwitch}
/>
</View>
</View>
</ListItem>
);
}
On my form Screen I have this:
<Controller
control={control}
render={({ field: { onChange, onBlur, value } }) => (
<SingleLineWithSwitch
title='Visible'
onBlur={onBlur}
onChangeText={onChange}
value={value}
/>
)}
name='visible'
/>
You need to lift the state isEnabled up to you parent component, that is your form.
This could look as follows.
export default function SingleLineWithSwitch(props) {
const isEnabled = props.enabled;
const setIsEnabled = props.setIsEnabled;
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<ListItem onPress={() => toggleSwitch()}>
<View style={Styles.listSingleCointainer}>
<SubtitleOne style={Styles.listTitle}>{props.title}</SubtitleOne>
<View style={Styles.listSwitchView}>
<Switch
thumbColor={props.thumbColor}
trackColor={props.trackColor}
style={Styles.switchControl}
value={isEnabled}
onValueChange={toggleSwitch}
/>
</View>
</View>
</ListItem>
);
}
Then, in your form
const [enabled, setIsEnabled] = useState(value)
<Controller
control={control}
render={({ field: { onChange, onBlur, value } }) => (
<SingleLineWithSwitch
title='Visible'
onBlur={onBlur}
onChangeText={onChange}
enabled={enabled}
setIsEnabled={setIsEnabled}
/>
)}
name='visible'
/>