How to use checkboxes in react native for both android and IOS? - react-native

I have a modal with diffrent tabs in my app in which user can filter the search result with categories in the modal . right now it is working but I simply put an event on a <TEXT> , I need some visual clue like checkbox for my options
{this.state.currentTab === 1 && (
<View>
<Text onPress={(text) => this.setGender(true)}>male</Text>
<Text onPress={(text) => this.setGender(false)}>female</Text>
</View>
)}
How Can I use checkbox instead of <TEXT> to use both in android and IOS?

You can use this library for the checkbox
" react-native-circle-checkbox "
import CircleCheckBox, {LABEL_POSITION} from 'react-native-circle-checkbox';
{this.state.currentTab === 1 && (
<View>
<CircleCheckBox
checked={true}
onToggle={(text) => this.setGender(true)}
labelPosition={LABEL_POSITION.RIGHT}
label="MALE"
/>
<CircleCheckBox
checked={true}
onToggle={(text) => this.setGender(false)}
labelPosition={LABEL_POSITION.RIGHT}
label="FEMALE"
/>
</View>
)}
Example: https://snack.expo.io/#msbot01/intrigued-marshmallows

Use This Component which I manually created. It renders same radio button on both platforms
const RenderRadio = (props) => {
const {
value, onChange, selectedValue
} = props;
const checked = value === selectedValue;
return (
<TouchableOpacity
style={{ flexDirection: 'row' }}
onPress={() => onChange(value)}
>
<View
style={{
width: 20,
height: 20,
borderRadius: 10,
borderWidth: 2,
borderColor: '#002451',
justifyContent: 'center',
alignItems: 'center',
}}
>
<View
style={{
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: checked ? '#002451' : 'white',
}}
/>
</View>
<Text style={{ fontSize: 15, marginLeft: 10 }}>{value}</Text>
</TouchableOpacity>
);
};
use it as
<RenderRadio onChange={this.setSelectedValue} selectedValue={selectedValue} value={value}/>
and set Your selected value as
setSelectedValue = (value) => {
this.setState(selectedValue : value)
}

You can use native-base library, that has more components which you can use for Search filters and this is more reliable, you can set it checked
using checked prop, that is boolean, like this :
import {
Icon,
CheckBox,
Spinner
} from "native-base";
<TouchableOpacity onPress={(text) => this.setGender(true)} >
<CheckBox checked ={tru}
onPress={(text) => this.setGender(true)} />
</TouchableOpacity>

Related

1st index hidden Item not hidding when swiping the another element - swiperFlatList React native

as you can see in the image, I have implemented adding Text inputs dynamically with the button press, everything is working perfectly only the 1st text input hidden item (Remove Button) not hiding when swiping the other text inputs.
const initialState = {
col1: '',
key: 0,
};
const [inputField, setInputField] = useState<Values[]>([initialState]);
<SwipeListView
data={inputField}
renderItem={data => renderItem(data)}
renderHiddenItem={data => renderHiddenItem(data)}
leftOpenValue={55}
rightOpenValue={-100}
disableRightSwipe={true}
ListHeaderComponent={
<View style={[styles.headingContainer]}>
<Text style={[styles.headingText]}>{Props.inputHeading}</Text>
</View>
}
ListFooterComponent={
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.addBtn}
activeOpacity={0.7}
onPress={onPressAddBtn}>
<Text style={styles.BtnText}>Add</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.submitBtn} activeOpacity={0.7}>
<Text style={styles.BtnText}>Submit</Text>
</TouchableOpacity>
</View>
}
style={{height: Dimensions.get('screen').height / 1.3}}
/>
const renderItem = (data: any) => {
return (
<TouchableHighlight key={data.item.key}>
<TextInput
placeholder="Hello"
onChangeText={e => handleChange(data.item.key, 'col1', e)}
value={data.item.col1}
style={[styles.textInput, Props.textInputStyle]}
// {...Props.textInputProps}
/>
</TouchableHighlight>
);
};
const renderHiddenItem = (rowData: any) => {
return (
<View
style={{
justifyContent: 'flex-end',
flexDirection: 'row',
alignItems: 'center',
}}>
<TouchableOpacity
activeOpacity={0.7}
style={{
backgroundColor: 'red',
justifyContent: 'center',
flexDirection: 'row',
width: 90,
height: 45,
alignItems: 'center',
borderRadius: 5,
}}>
<Text style={{color: 'white'}}>Remove</Text>
</TouchableOpacity>
</View>
);
};
but other all element's swipe is working as expected only the first element is not working as expected
found solution by adding keyExtractor={item => item.key.toString()} to swiper flatlist.

Auto Focus Property is not working in Text Input Component on React Native

I am making a Search Bar and I want they keyboard to open up once the Search button has been clicked however the autoFocus property of the TextInput is not working. What am I doing wrong?
Here's the code:
const SearchBar = () => {
return (
<View style={{ flex: 1 }}>
<TextInput placeholder="Search"
style={{ width: Dimensions.get('screen').width, height: 50, borderWidth: 1,
borderRadius: 20 }}
autoFocus={true}
/>
</View>
)
}
const Search = () => {
return (
<TouchableWithoutFeedback onPress={()=>Keyboard.dismiss()} >
<SearchBar />
</TouchableWithoutFeedback>
)
}
umm, ideally autoFocus should work on mounting of this comp.
If its not, workaround would be explicitly adding a ref and focusing it
class ABC extends .. {
constructor(props){
...
this.textInput = React.createRef();
}
componentDidMount(){
this.textInput.current.focus();
}
SearchBar = () => {
return (
<View style={{ flex: 1 }}>
<TextInput placeholder="Search"
style={{ width: Dimensions.get('screen').width, height: 50, borderWidth: 1,
borderRadius: 20 }}
autoFocus={true}
ref={this.textInput}
/>
</View>
)
}
}

Multiple item data. Show the data as clicked in the dynamically modal with react-native

FOOD> PIZZA> clicking on any pizza opens a modal. I want to show the information of the pizza clicked in this modal. I looked at many similar examples but I could not get out of it. So I need help. I add some parts of the code below. At the same time, the code is available in the expo and the link below
snack.expo.io/#ibrahimyolbir/e48b05
accordion
<Accordion
dataArray={this.state.menus}
animation={true}
expanded={true}
renderHeader={this._renderHeader}
renderContent={this._renderContent}
/>
my open modal button in the render content
onPress={this.triggerModal(food)}
_renderContent = (item) => {
return (
<List>
{
item.food.map((food, index) => {
return (
<ListItem style={{
backgroundColor: "#f0f0f5",
padding: 10,
marginLeft: 0,
paddingRight: 10,
fontStyle: "italic",
listStyleType: "none",
flexDirection: "row",
justifyContent: "space-between"
}}>
<TouchableOpacity
onPress={this.triggerModal(food)}
style={{
flexDirection: "row",
justifyContent: "space-between"
}}
>
<Left style={{
maxWidth: 57
}}>
<Thumbnail source={require("../assets/images/left-food-icon.png")} />
</Left>
<Body>
<Text >{food.name}</Text>
<Text note >{food.description}</Text>
</Body>
<Right>
<Text >{food.price} :-</Text>
</Right>
</TouchableOpacity>
</ListItem>
)
}
)
}
</List>
);
}
MODAL
<Modal
style={{ marginTop: 122 }}
isVisible={this.state.display}
visible={this.state.display}
onSwipeComplete={() => this.setState({ isVisible: false })}
onSwipeThreshold={1}
swipeDirection="down"
animationType="slide"
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={{ flex: 1, backgroundColor: "#fff" }}>
<Text>Hello!</Text>
<TouchableOpacity onPress={this.closeDisplay} style={{ marginTop: 40, marginLeft: 150 }}>
<Text> CLOSE MODAL </Text>
</TouchableOpacity>
{/* <Text> {this.state.menus} </Text> */}
</View>
</Modal>
One of the way can be:
1)Create a new state
currentChildData:[],
currentParentData:[],
2)Pass parent id and child index in onPress event
<TouchableOpacity onPress={()=>this.triggerModal(item.id,index)}
3)Using that passed index and parent id,we can extract relevant information about(to be clicked item) from menus state
triggerModal = (ParentIndex,childIndex) => {
this.setState(prevState => {
let ParentData=[...prevState.menus].find(each=>each.id==ParentIndex)
return {
display: true,
currentChildData: ParentData.food[childIndex],
currentParentData: ParentData,
}
});
}
4)Now we have information of(to be clicked item) in our state. We then can use it like (name of item shown below) inside Modal
<Text>{this.state.currentChildData.name}</Text>
Working Code: https://snack.expo.io/By_QVbPMI
U missed the key from mapped array in a ListItem component. Add it as a prop key={Index} .
Also U need item from map as argument in ur onPress, cuz u need to push visited/selected elements to the state. {()=>this.openModal(itemFromMap)}
And then u can manipulate with data like u need.
As I can understood u have array of objects. Object.keys(itemFromMap).map(...
And return data to the needed part of ur modalInnerContainer.

How to fix keyboard from hiding input fields in React Native

I’m setting up a new component,
and the keyboard covers the fields
This is for a new component
<KeyboardAwareScrollView enableOnAndroid={true} extraScrollHeight={50} enableAutomaticScroll={true}>
<View style={{ paddingHorizontal: 20 }}>
<View>
<FloatingLabelInput
onRef={(ref) => {
this.inputs['firstName'] = ref
}}
onSubmitEditing={() => {
this.focusNextField('lastName')
}}
label={i18n.t('t_driver_registration_first_name_label')}
onChangeText={(text) => this.onChangeInputText('firstName', text)}
keyboardType='default'
maxLength={20}
value={form.firstName}
labelStyle={Style.inputLabel}
basicColor={GStyle.GREEN}
inputTextColor={Color(GStyle.BLACK).alpha(.7)}
editable={mode !== DriverFormMode.EDIT}
/>
I expect the keyboard will not cover my fields.
Wrap your view in this to scroll automatically on input focus. Do:
<KeyboardAvoidingView style={{ flex: 1, flexDirection: 'column',justifyContent: 'center',}} behavior="padding" enabled keyboardVerticalOffset={100}>
<ScrollView>
<View style={Styles.row}>
//your view
</View>
</ScrollView>
</KeyboardAvoidingView>
<View style={Styles.row}> This is just a Stylesheet e.g. Create a new StyleSheet:
const Styles = StyleSheet.create({
row: {
borderRadius: 4,
borderWidth: 0.5,
borderColor: '#d6d7da',
},
title: {
fontSize: 19,
fontWeight: 'bold',
},
activeTitle: {
color: 'red',
},
});
Use a StyleSheet:
<View style={Styles.row}>
<Text style={[Styles.title, this.props.isActive && styles.activeTitle]} />
</View>

React Redux Form checkbox and dropdown field in React Native?

I am trying to build a form in React Native using React Redux Form but I can use the <TextInput> for Email & Password but now I would like to use some checkboxes and dropdowns. Their documentationm doesn't provide an React Native guideline or any examples as they use simply <Input> tag for any inputs but how do i use this in React Native?
Here is my field render I use for email:
const renderField = ({ label, type, keyboardType, name, meta: { touched, error }, input: { onChange, ...restInput } }) => {
return (
<View style={{ flexDirection: 'column', height: 70, alignItems: 'flex-start' }}>
<View style={{ flexDirection: 'row', height: 30, alignItems: 'center', borderColor: 'black', borderBottomWidth: 1, }}>
<FontAwesome name='email-outline' size={18} color='#cccccc' style={{ paddingLeft: 2 }} />
<TextInput style={{ height: 37, width: 280, paddingLeft: 10, fontSize: 20 }}
keyboardType={keyboardType} onChangeText={onChange} {...restInput}
placeholder={label}
>
</TextInput>
</View>
{touched && ((error && <Text style={{ color: 'red', }}>{error}</Text>))}
</View>);
};
<Field keyboardType='email-address' type='email' label='Email' component={renderField} name='email' />
And what's the problem?
Just create a checkboxField component that you'll use instead of renderField in the places you need. And simply use the onChange function from the props to set a value and value as the value itself.
Here is an example that would be easier to understand:
const renderField = ({ input: { onChange, value } }) => {
return (
<View>
<Switch
onValueChange={(value) => onChange(value)}
value={value}
/>
</View>
);
};