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>
);
}
}
Related
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;
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",
},
});
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
Trying to apply a default query in the reactive search component and it doesn't have an effect
import React from 'react';
import {
NavigationScreenProps,
NavigationScreenConfig, NavigationActions,
} from 'react-navigation';
import {
ChatHeader,
ChatHeaderNavigationStateParams,
} from '#src/components/messaging';
import {
Conversation,
} from '#src/core/model';
import {conversation5} from '#src/core/data/conversation';
import {StyleSheet, Text, Image, TouchableWithoutFeedback} from 'react-native';
import {
ReactiveBase,
DataSearch,
ReactiveList,
} from '#appbaseio/reactivesearch-native';
import {ScrollView, View} from 'react-native';
import {Icon, ListItem} from '#kitten/ui';
import LottieView from 'lottie-react-native';
import {SearchHeader} from '#src/components/search/search.header';
import {userProvider} from '../../../../domain/auth/UserProvider';
import {Screen} from '../../../../core/navigation/screens';
import Tts from 'react-native-tts';
import {StarIconOutline} from '#src/assets/icons';
import axios, {AxiosError, AxiosResponse} from 'axios';
import {Config} from '../../../../constants/Config';
import {User} from '#domain/models';
import DoubleClick from 'react-native-double-tap';
import {Notification} from 'react-native-in-app-message';
import AnimatedLoader from 'react-native-animated-loader';
interface State {
newMessageText: string;
conversation: Conversation;
isLoading: boolean;
message: string;
}
const styles = StyleSheet.create({
container: {
padding: 10,
marginTop: 25,
},
image: {
width: 100,
height: 100,
},
result: {
flexDirection: 'row',
width: '100%',
margin: 5,
alignItems: 'center',
},
notification: {
flexDirection: 'row',
width: '100%',
margin: 5,
padding: 5,
alignItems: 'flex-start',
},
item: {
flexDirection: 'column',
paddingLeft: 10,
},
title: {
fontWeight: 'bold',
},
lottie: {
width: 100,
height: 100,
},
iconx: {
width: 50,
height: 40,
marginLeft: -3,
marginBottom: -10,
padding: 5,
},
notificationText: {
marginTop: 11,
},
});
export class SearchContainer extends React.Component<NavigationScreenProps, State> {
private notification: Notification;
private token: string;
public state: State = {
newMessageText: '',
conversation: conversation5,
isLoading: false,
message: '',
};
private infiniteAnimationIconRef: React.RefObject<Icon> = React.createRef();
static navigationOptions: NavigationScreenConfig<any> = ({navigation, screenProps}) => {
const headerProps: ChatHeaderNavigationStateParams = {
interlocutor: navigation.getParam('interlocutor', conversation5.interlocutor),
lastSeen: navigation.getParam('lastSeen', 'today'),
onBack: navigation.getParam('onBack'),
onProfile: navigation.getParam('onProfile'),
};
const header = (navigationProps: NavigationScreenProps) => {
return (
<SearchHeader
{...navigationProps}
{...headerProps}
/>
);
};
return {...navigation, ...screenProps, header};
};
public async componentWillMount(): void {
this.props.navigation.setParams({
onBack: this.onBackPress,
});
await userProvider.get().then((data) => {
this.token = data.token;
}).catch(() => {
this.props.navigation.navigate(Screen.Login);
});
}
public componentDidMount() {
this.setState({
isLoading: false,
});
}
private onBackPress = (): void => {
this.props.navigation.goBack(null);
};
private say(deText): void {
Tts.setDefaultLanguage('de-DE');
Tts.setDucking(true);
Tts.speak(deText);
}
private star(id): void {
this.setState({isLoading: true});
axios.post(Config.service.stars.url, {
sentence_id: id,
}, {
headers: {
'Authorization': `Bearer ${this.token}`,
},
}).then((response: AxiosResponse<UserData>) => {
this.setState({message: 'Star added!'});
setTimeout(() => this.notification.show(), 100);
this.setState({isLoading: false});
}).catch((error: AxiosError) => {
let errorMessage = null;
try {
const code = error.response.request.status;
if (code === 401) {
this.props.navigation.navigate(Screen.Login);
} else if (code === 422) {
errorMessage = 'Star was added already for this sentence!';
} else {
errorMessage = 'Service is unavailable, please try again in a few!';
}
} catch (e) {
errorMessage = 'Service is unavailable, please try again in a few!';
}
this.setState({...this.state, message: errorMessage});
setTimeout(() => this.notification.show(), 100);
this.setState({isLoading: false});
});
}
public render(): React.ReactNode {
return (
<ReactiveBase
app='myapp'
url='http://xxx.xxxxxx.io'
headers={{'X-Api-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxx'}}>
<View>
<DataSearch
componentId='searchbox'
dataField={[
'sentence',
'sentence.en',
'sentence.de',
'raw.translated',
]}
value='1'
highlight={true}
placeholder='words or expressions'
defaultQuery={() => ({
query: {
match: {
message: {
query: 'test',
},
},
},
})}
autosuggest={false}
/>
</View>
<Notification
customComponent={(
<View style={styles.notification}>
<LottieView
style={styles.iconx}
source={require('#src/animations/warning.json')}
colorFilters={[{
keypath: 'button',
color: '#F00000',
}, {
keypath: 'Sending Loader',
color: '#F00000',
}]}
autoPlay
loop={true}
/>
<Text style={styles.notificationText}>{this.state.message}</Text>
</View>
)}
ref={(c) => this.notification = c}
/>
<AnimatedLoader
visible={this.state.isLoading}
overlayColor='rgba(255,255,255,0.75)'
source={require('#src/animations/loader.json')}
animationStyle={styles.lottie}
speed={1}
/>
<ScrollView
stickyHeaderIndices={[1]}
nativeID={'scoller'}
>
<View>
<ReactiveList
componentId='results'
dataField='sentence.de'
size={7}
showResultStats={false}
pagination={true}
infiniteScroll={true}
scrollTarget={'scroller'}
react={{
and: 'searchbox',
}}
defaultValue={'Harry Potter'}
onData={(res, idx) => (
<View style={styles.result} key={res._id}>
<DoubleClick
singleTap={() => {
this.star(res._id);
}}
doubleTap={() => {
}}
delay={1000}
>
<Icon name='star-outline' fill='#FF9999' width='30' height='50'/>
</DoubleClick>
<ListItem
onPress={() => this.say(res.sentence.de)}
title={res.sentence.de}
description={res.raw.translated}
/>
</View>
)}
/>
</View>
</ScrollView>
</ReactiveBase>
);
}
}
<DataSearch
componentId='searchbox'
dataField={[
'sentence',
'sentence.en',
'sentence.de',
'raw.translated',
]}
value='1'
highlight={true}
placeholder='words or expressions'
defaultQuery={() => ({
query: {
match: {
message: {
query: 'test',
},
},
},
})}
autosuggest={false}
/>
Try this (i.e. use filter instead of should):
<ReactiveComponent
componentId='filterbox'
customQuery={props => ({
query: {
'bool': {
'filter': [{
'ids': {
'type': 'mydoctype',
'values': ['TK6IRm4BK9UoLvJay0OC', 'Ra6IRm4BK9UoLvJaykMD'],
},
}]
},
}
})}
/>
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 })} />