How to get selected item in RadioGroup in React native? - react-native

How can i get selected value from RadioGroup.
state = {
gender: '',
data: [
{
label: 'male',
value: "Male",
},
{
label: 'female',
value: "Female",
}
],
}
render() {
return (
<View style={styles.radioGroupContainer}>
<Text style={styles.textLableStyle}>Select Gender</Text>
<RadioGroup style={alignItems = 'flex-start'}
radioButtons={this.state.data}
onPress={
this.onPress
} />
</View>
)
}
Note: On selection of radio button i want value in gender variable.

Install the package by entering the below command in your project root directory.
npm i react-native-radio-buttons-group --save
Basic Usage
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import RadioGroup from 'react-native-radio-buttons-group';
export default class Vertical extends Component {
state = {
data: [
{
label: 'Default value is same as label',
},
{
label: 'Value is different',
value: "I'm not same as label",
},
{
label: 'Color',
color: 'green',
},
{
disabled: true,
label: 'Disabled',
},
{
label: 'Size',
size: 32,
},
],
};
// update state
onPress = data => this.setState({ data });
render() {
let selectedButton = this.state.data.find(e => e.selected == true);
selectedButton = selectedButton ? selectedButton.value : this.state.data[0].label;
return (
<View style={styles.container}>
<Text style={{ fontSize: 18, marginBottom: 50 }}>
Value = {selectedButton}
</Text>
<RadioGroup radioButtons={this.state.data} onPress={this.onPress} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
Output

make the RadioGroup like that , only giving the RadioGroup tag . by putting that code you will get the value in gender state.
<RadioGroup style={alignItems = 'flex-start'}
radioButtons={this.state.data}
onPress={data => this.setState({gender: data })} />

Related

How to display list of countries as webpage in expo react native

I am beginner with react native expo, just creating my first project. I am able to make a flat list and app is working great so far.
However now I need to make something like this,
As being newbie, I am not sure where to start, It seems like a webview is used but I am not sure how to put flatview into webview, or am I completely on wrong track ?
This is what I coded so far,
import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar } from 'react-native';
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const App = () => {
const renderItem = ({ item }) => (
<Item title={item.title} />
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
export default App;
Result:
Code:
import React from "react";
import { FlatList, SafeAreaView, StyleSheet, Text, View } from "react-native";
class App extends React.Component {
state = {
data: [
{ id: "00", name: "Mazda RX-7" },
{ id: "01", name: "McLaren F1" },
{ id: "02", name: "Mini Cooper" },
{ id: "03", name: "BMW 645 Ci" }
]
};
render() {
const columns = 3;
return (
<SafeAreaView>
<FlatList
data={createRows(this.state.data, columns)}
keyExtractor={item => item.id}
numColumns={columns}
renderItem={({ item }) => {
if (item.empty) {
return <View style={[styles.item, styles.itemEmpty]} />;
}
return (
<View style={styles.item}>
<Text style={styles.text}>{item.name}</Text>
</View>
);
}}
/>
</SafeAreaView>
);
}
}
function createRows(data, columns) {
const rows = Math.floor(data.length / columns);
let lastRowElements = data.length - rows * columns;
while (lastRowElements !== columns) {
data.push({
id: `empty-${lastRowElements}`,
name: `empty-${lastRowElements}`,
empty: true
});
lastRowElements += 1;
}
return data;
}
const styles = StyleSheet.create({
item: {
alignItems: "center",
backgroundColor: "#dcda48",
flexBasis: 0,
flexGrow: 1,
margin: 4,
padding: 20
},
itemEmpty: {
backgroundColor: "transparent"
},
text: {
color: "#333333"
}
});
export default App;

How to create a multi-select on React-Native-Super-Grid

I am new in React Native and I have been trying to implement a multi-select on a Flatlist. I recently found the react-native-super-grid component and I have been trying to customize it so I maybe able to do a multi-select and no luck thus far.
Am I on the right track, or is there a component that does a grid and multi-select?
Thank you, :'(
import React, { Component } from 'react'
import { View, StyleSheet, Text } from 'react-native'
import { FlatGrid } from 'react-native-super-grid'
export default class GridFlatlist extends Component {
render() {
const items = [
{ name: 'Pick n Pay', code: '#1abc9c' }, { name: 'EMERALD', code: '#2ecc71' },
{ name: 'PETER RIVER', code: '#3498db' }, { name: 'AMETHYST', code: '#9b59b6' },
{ name: 'WET ASPHALT', code: '#34495e' }, { name: 'GREEN SEA', code: '#16a085' },
{ name: 'NEPHRITIS', code: '#27ae60' }, { name: 'BELIZE HOLE', code: '#2980b9' },
{ name: 'WISTERIA', code: '#8e44ad' }, { name: 'MIDNIGHT BLUE', code: '#2c3e50' },
{ name: 'SUN FLOWER', code: '#f1c40f' }, { name: 'CARROT', code: '#e67e22' },
{ name: 'ALIZARIN', code: '#e74c3c' }, { name: 'CLOUDS', code: '#ecf0f1' },
{ name: 'CONCRETE', code: '#95a5a6' }, { name: 'ORANGE', code: '#f39c12' },
{ name: 'PUMPKIN', code: '#d35400' }, { name: 'POMEGRANATE', code: '#c0392b' },
{ name: 'SILVER', code: '#bdc3c7' },
];
return (
<FlatGrid
itemDimension={110}
items={items}
style={styles.gridView}
renderItem={({ item, index }) => (
<View style={[styles.itemContainer, { backgroundColor: item.code }]}>
<Text style={styles.itemName}>{item.name}</Text>
<Text style={styles.itemCode}>{item.code}</Text>
</View>
)} />
)
}
}
const styles = StyleSheet.create({
gridView: {
marginTop: 20,
flex: 1,
},
itemContainer: {
justifyContent: 'flex-end',
padding: 10,
height: 110,
},
itemName: {
fontSize: 16,
color: '#fff',
fontWeight: '600',
},
itemCode: {
fontWeight: '600',
fontSize: 12,
color: '#fff',
},
})
You can use a flatlist to create a multi select very simply. Only thing is react native doesnt have a checkbox that works in both Android and IOS. The below example is for Android and you can use the Checkbox from react native elements to support both platforms.
Here's the code for the solution.
const CheckList = props => {
const [data, setData] = useState([]);
useEffect(() => {
setData(props.data);
}, []);
const OnCheckChange = id => {
const arr = [...data];
const item = arr.find(item => item.id === id);
item.isChecked = !item.isChecked;
setData(arr);
// can use a callback to update parent from here
};
return (
<FlatList
data={data}
renderItem={({ item }) => {
return (
<View style={{ flexDirection: "row" }}>
<CheckBox
value={item.isChecked}
onValueChange={() => OnCheckChange(item.id)}
/>
<Text>{item.name}</Text>
</View>
);
}}
/>
);
};
const items = [
{ id: 1, name: "Pick n Pay", code: "#1abc9c" },
{ id: 2, name: "EMERALD", code: "#2ecc71" },
{ id: 3, name: "PETER RIVER", code: "#3498db" },
{ id: 4, name: "AMETHYST", code: "#9b59b6" },
{ id: 5, name: "WET ASPHALT", code: "#34495e" },
{ id: 6, name: "GREEN SEA", code: "#16a085" },
{ id: 7, name: "NEPHRITIS", code: "#27ae60" },
{ id: 8, name: "BELIZE HOLE", code: "#2980b9" }
];
class App extends Component {
render() {
return (
<View style={styles.app}>
<CheckList data={items} />
<Button onPress={() => {}} title="Example button" />
</View>
);
}
}

React Native - Search an array off Object using react hooks

I have an array off Object inside a variable named data.
The array looks like this:
const data = [
{
"id": "0.804802585702977",
"value": "Bar",
},
{
"id": "0.9359341974615858",
"value": "Mar",
},
{
"id": "0.4182922963461958",
"value": "Naba",
},
{
"id": "0.6132336648416628",
"value": "Socerr",
},
{
"id": "0.060587558948085984",
"value": "Mall",
},
]
I want to create a search bar to search all the value inside that array and if the search text is equal to the value inside that array the user will be able to see that value?
Please help?
You need to use filter function to search/Sort data from Array. Please check following it may solve you problem.
import React, { useState } from "react";
import { Text, TextInput, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
// You can import from local files
import AssetExample from "./components/AssetExample";
// or any pure javascript modules available in npm
import { Card } from "react-native-paper";
const data = [
{
id: "0.804802585702977",
value: "Bar",
},
{
id: "0.9359341974615858",
value: "Mar",
},
{
id: "0.4182922963461958",
value: "Naba",
},
{
id: "0.6132336648416628",
value: "Socerr",
},
{
id: "0.060587558948085984",
value: "Mall",
},
];
export default function App() {
let [filteredData, setFilteredData] = useState(data);
function _searchFilterFunction(searchText, data) {
let newData = [];
if (searchText) {
newData = data.filter(function(item) {
const itemData = item.value.toUpperCase();
const textData = searchText.toUpperCase();
return itemData.includes(textData);
});
setFilteredData([...newData]);
} else {
setFilteredData([...data]);
}
}
return (
<View style={styles.container}>
<Text style={styles.paragraph}>Search Here.</Text>
<TextInput
style={styles.input}
underlineColorAndroid="transparent"
placeholder="Search"
placeholderTextColor="#9a73ef"
autoCapitalize="none"
onChangeText={(value) => {
_searchFilterFunction(value, data);
}}
/>
{filteredData.map((item, index) => {
return <Text style={styles.paragraph}>{item.value}</Text>;
})}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ecf0f1",
padding: 8,
},
input: {
margin: 15,
height: 40,
paddingLeft: 10,
borderRadius: 2,
borderColor: "#7a42f4",
borderWidth: 1,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
},
});

How to make search bar with dropdown list in react-native?

I want to create a search bar with a drop-down list with react-native, more like this image
I know there are lots of libraries regarding these which makes my task easy but I have just started with react-native so for my knowledge I wanna know how these things are made.
I came across tutorials of how to make a search bar with live search and update the flatlist by filtering the data based on your search but none of them has a dropdown list involved.
Code updating my flatlist based on search word is already done, I need to just display this flatlist in the form of a dropdown list.
A link to tutorial or sample code would be helpful.
Check below example which i created using flatlist and TextInput. Items are displayed in the form of a dropdown list when you search items. i think this will help you.
import React, { Component } from "react";
import { View, Text, FlatList, TextInput, ListItem } from "react-native";
class FlatListDropDown extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
value: "",
};
this.arrayNew = [{ name: "Robert" }, { name: "Bryan" }, { name: "Vicente" }, { name: "Tristan" }, { name: "Marie" }, { name: "Onni" }, { name: "sophie" }, { name: "Brad" }, { name: "Samual" }, { name: "Omur" }, { name: "Ower" }, { name: "Awery" }, { name: "Ann" }, { name: "Jhone" }, { name: "z" }, { name: "bb" }, { name: "cc" }, { name: "d" }, { name: "e" }, { name: "f" }, { name: "g" }, { name: "h" }, { name: "i" }, { name: "j" }, { name: "k" }, { name: "l" }];
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#CED0CE",
}}
/>
);
};
searchItems = (text) => {
const newData = this.arrayNew.filter((item) => {
const itemData = `${item.name.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
data: newData,
value: text,
});
};
renderHeader = () => {
return (
<TextInput
style={{ height: 60, borderColor: "#000", borderWidth: 1 }}
placeholder=" Type Here...Key word"
onChangeText={(text) => this.searchItems(text)}
value={this.state.value}
/>
);
};
render() {
return (
<View
style={{
flex: 1,
padding: 25,
width: "98%",
alignSelf: "center",
justifyContent: "center",
}}
>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<Text style={{ padding: 10 }}>{item.name} </Text>
)}
keyExtractor={(item) => item.name}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
</View>
);
}
}
export default FlatListDropDown;
Feel free for doubts

Redux-form, onChange(value) returns undefined, custom Radio component

I am using Redux-form with a custom Radio Group and Button components. When i select a radio button, redux-logger seems to show that the state is updated with the correct values. However checked always returns false, and so the radio button style never gets updated.
console.log(value) returns the correct value
console.log(onChange(value) always returns undefined
console.log(checked) always returns false
RadioGroup.js
import React from 'react';
import PropTypes from 'prop-types';
import { View, Text, StyleSheet } from 'react-native';
import RadioButton from '../components/RadioButton';
import { COLOR_PRIMARY } from '../constants';
const styles = StyleSheet.create({
errorStyle: {
color: COLOR_PRIMARY,
},
});
const RadioGroup = (props) => {
const { radios, input: { value, onChange }, meta: { touched, error } } = props;
return (
<View>
{radios.map(radio => (
<RadioButton
key={radio.label}
{...radio}
onChange={onChange}
checked={radio.value === value}
/>
))}
{touched &&
(error && (
<View>
<Text style={styles.errorStyle}>{error}</Text>
</View>
))}
</View>
);
};
RadioGroup.propTypes = {
radios: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired,
}),
).isRequired,
meta: PropTypes.shape({
touched: PropTypes.bool.isRequired,
error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
}).isRequired,
input: PropTypes.shape({
value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired,
onChange: PropTypes.func.isRequired,
}).isRequired,
};
export default RadioGroup;
RadioButton.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
import { COLOR_PRIMARY, TEXT_PRIMARY } from '../constants';
const styles = StyleSheet.create({
container: {
marginBottom: 20,
flexDirection: 'row',
alignItems: 'center',
},
circle: {
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: COLOR_PRIMARY,
alignItems: 'center',
justifyContent: 'center',
},
circleFilled: {
height: 14,
width: 14,
borderRadius: 7,
backgroundColor: COLOR_PRIMARY,
},
labelStyle: {
color: TEXT_PRIMARY,
marginLeft: 10,
marginRight: 10,
},
});
export default class RadioButton extends Component {
handlePress = () => {
const { value, onChange, checked } = this.props;
onChange(value);
console.log(onChange(value));
console.log(value);
console.log(checked);
};
render() {
const { checked, label } = this.props;
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.handlePress} style={styles.radioStyle}>
<View style={styles.circle}>
<View style={checked ? styles.circleFilled : null} />
</View>
</TouchableOpacity>
<Text style={styles.labelStyle}>{label}</Text>
</View>
);
}
}
RadioButton.propTypes = {
checked: PropTypes.bool.isRequired,
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired,
onChange: PropTypes.func.isRequired,
};
Form.js
<Field
name="sex"
radios={[{ label: 'Male', value: 'Male' }, { label: 'Female', value: 'Female' }]}
component={RadioGroup}
/>
So is there some problem with how i am using onChange?