React Native flatlist with checkbox - react-native

I am new to react native. I am writing the code in class component, I need a flatlist with checkbox that allow multiple select, add the selected data could be save in a array and pass to other screen. I have no idea about that.. Can anyone help??

Try this example:
import React, { Component } from 'react';
import { View, Text, Image, FlatList, TextInput } from 'react-native';
import { ListItem, Body } from 'native-base';
import CheckBox from '#react-native-community/checkbox';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
serachdata: [],
selectedId: []
};
}
componentDidMount(){
this.ApiCalling();
}
ApiCalling = () => {
const url = "YOUR_API"
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({data: res.data})
this.setState({serachdata: res.data})
})
.catch(error => {
console.log("error ", error)
})
}
onCheckBoxPress = (id) => {
let checkboxes = this.state.selectedId;
if(checkboxes && checkboxes.includes(id)){
checkboxes.splice( checkboxes.indexOf(id), 1 );
} else {
checkboxes = checkboxes.concat(id);
}
this.setState({selectedId:checkboxes})
console.log("selectde checkbox id: ", checkboxes)
}
_filter = (text) => {
const newData = this.state.data.filter(item => {
const itemData = `${item.first_name.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({serachdata:newData})
}
render(){
return(
<View style={{ marginTop: 50 }}>
<TextInput
autoCapitalize='none'
autoCorrect={false}
style={{ height: 40, borderColor: 'gray', borderWidth: 1, margin:10 }}
status='info'
placeholder='Search'
onChangeText={(text) => this._filter(text)}
textStyle={{ color: '#000' }}
/>
<FlatList
data={this.state.serachdata}
keyExtractor={(item, index) => String(index)}
renderItem={({item, index}) => {
return(
<ListItem key={index}>
<CheckBox
disabled={false}
value={this.state.selectedId && this.state.selectedId.includes(item.id)}
onChange={()=>this.onCheckBoxPress(item.id)}
/>
<Body>
<View style={{flexDirection:'row', justifyContent:'space-between'}}>
<Image source={{ uri: item.avatar }} style={{ height: 100, width: 100 }} />
<Text>{item.first_name}</Text>
<Text>{item.email}</Text>
{/* <Text>{item.name.last}</Text> */}
</View>
</Body>
</ListItem>)}}
/>
</View>
)
}
};

Related

Searching in Expo's FlatList

I used this tutorial but it didn't work (if you are interested, check out my last post). Any suggestions to make a working search for a flatlist?
I have a list of 100 things and just by inserting the name in a search bar, the flatlist should update with the results.
Try using react-native-searchable-flatlist
import React, { Component } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';
import { ListItem, SearchBar } from 'react-native-elements';
class FlatListDemo extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
error: null,
};
this.arrayholder = [];
}
componentDidMount() {
this.makeRemoteRequest();
}
makeRemoteRequest = () => {
const url = `https://randomuser.me/api/?&results=20`;
this.setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: res.results,
error: res.error || null,
loading: false,
});
this.arrayholder = res.results;
})
.catch(error => {
this.setState({ error, loading: false });
});
};
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '86%',
backgroundColor: '#CED0CE',
marginLeft: '14%',
}}
/>
);
};
searchFilterFunction = text => {
this.setState({
value: text,
});
const newData = this.arrayholder.filter(item => {
const itemData = `${item.name.title.toUpperCase()} ${item.name.first.toUpperCase()} ${item.name.last.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
data: newData,
});
};
renderHeader = () => {
return (
<SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={text => this.searchFilterFunction(text)}
autoCorrect={false}
value={this.state.value}
/>
);
};
render() {
if (this.state.loading) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{ flex: 1 }}>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<ListItem
leftAvatar={{ source: { uri: item.picture.thumbnail } }}
title={`${item.name.first} ${item.name.last}`}
subtitle={item.email}
/>
)}
keyExtractor={item => item.email}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
</View>
);
}
}
export default FlatListDemo;

onPress not working in React Native Flatlist

My onPress handler is not working when someone clicks on Flatlist item.
Video of this issue
https://u.pcloud.link/publink/show?code=XZWGOUkZmDLPeKQOQJJzxnqFB8Q21X3acT7k
Here is the code:
import React, { useState, useEffect } from 'react';
import { View, Text, Image, FlatList, ActivityIndicator } from 'react-native';
import { TouchableNativeFeedback } from 'react-native-gesture-handler';
import axios from 'axios';
export default function _AjaxApp() {
const [postList, setPostList] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const loadData = (append = false) => {
let url = "https://edristi.in/wp-json/wp/v2/posts?per_page=20&page=" + currentPage;
setIsLoading(true);
setCurrentPage(currentPage + 1);
axios.get(url).then((r) => {
if (append) {
setPostList(postList.concat(r.data));
} else {
setPostList(r.data);
}
setIsLoading(false);
}).catch((e) => {
console.log(e);
});
}
useEffect(() => {
loadData();
}, [])
let Loader = <></>
if (isLoading) {
Loader = <ActivityIndicator></ActivityIndicator>
}
return (
<View>
<View style={{padding:20, backgroundColor:"#4342fe"}}>
<Text style={{color:"white"}}>Edristi App</Text>
</View>
<FlatList
data={postList}
renderItem={({ item, index, separators }) => <PostCard postList={postList} {...item} index={index} />}
keyExtractor={r => r.id + "-" + Math.random().toString()}
removeClippedSubviews={true}
maxToRenderPerBatch={2}
ListFooterComponent={Loader}
onEndReachedThreshold={0.5}
onEndReached={() => {
loadData(true);
}}
/>
</View>
);
}
class PostCard extends React.PureComponent {
onPressHandler() {
console.log("Clicked");
alert("Clicked");
}
render() {
let image = <></>
if (this.props.jetpack_featured_media_url.trim() !== "") {
image = <Image style={{ flex: 1 }} source={{
//uri: this.props.featuredimage,
uri: this.props.jetpack_featured_media_url,
}} />
}
// console.log(this.props.jetpack_featured_media_url);
return <TouchableNativeFeedback onPress={()=>{
this.onPressHandler();
}}>
<View style={{ margin: 10 }}>
<Text style={{ fontSize: 17, lineHeight: 23, fontWeight: "600" }}>{ this.props.title.rendered}</Text>
</View></TouchableNativeFeedback>
}
}
Try to import 'TouchableNativeFeedback' from 'react-native' instead of 'react-native-gesture-handler'.

How to use ScrollToIndex in React Native?

I use a FlatList to display search results.
<View>
<FlatList
data={this.state.films}
keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => <FilmItem film={item}/>}
/>
</View>
However, when the user starts a second search, this list does not restart to index 0. So I would like to add ScrollToIndex or viewPosition. I tried this but it doesn't work :
<View>
<FlatList
data={this.state.films}
keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => <FilmItem film={item}/>}
scrollToItem={(index) => {0}}
/>
</View>
Could you please explain me why this is wrong and what would be the best solution ?
Thanks a lot,
Try this... I made a bunch of changes and have put comments:
// Components/Search.js
import React from "react";
import {StyleSheet, View, TextInput, Button, Text, FlatList, ActivityIndicator} from "react-native";
import FilmItem from "./filmItem";
import {getFilmsFromApiWithSearchedText} from "../API/TMDBApi";
class Search extends React.Component {
flatListRef = null; // declaring this here to make it explicit that we have this available
constructor(props) {
super(props);
this.searchedText = "";
this.state = {
films: [],
isLoading: false,
};
}
_loadFilms = () => {
// needs to be an arrow function so `this` is bound to this component
this.scrollToIndex(); // assumed you meant to actually call this?
if (this.searchedText.length > 0) {
this.setState({isLoading: true});
getFilmsFromApiWithSearchedText(this.searchedText).then(data => {
this.setState({
films: data.results,
isLoading: false,
});
});
}
};
// needs arrow to use `this`
_searchTextInputChanged = text => {
this.searchedText = text;
};
// needs arrow to use `this`
_displayLoading = () => {
// better to return null if not loading, otherwise return loading indicator
if (!this.state.isLoading) return null;
return (
<View style={styles.loading_container}>
<ActivityIndicator size='large' />
</View>
);
};
scrollToIndex = () => {
// you previously had this inside another method
this.flatListRef && this.flatListRef.scrollToIndex({index: 1}); // checking it exists first
};
render() {
return (
<View style={styles.main_container}>
<TextInput
style={styles.textinput}
placeholder='Titre du film'
onChangeText={text => this._searchTextInputChanged(text)}
onSubmitEditing={this._loadFilms} // no need to create a new anonymous function here
/>
<Button title='Rechercher' onPress={this._loadFilms} />
<View>
<FlatList
data={this.state.films}
ref={ref => (this.flatListRef = ref)}
keyExtractor={item => item.id.toString()}
onEndReachedThreshold={1} // corrected typo
onEndReached={() => {
console.log("TOC");
}}
renderItem={({item}) => <FilmItem film={item} />}
/>
</View>
{this._displayLoading()}
</View>
);
}
}
const styles = StyleSheet.create({
main_container: {
marginTop: 60,
padding: 15,
flex: 1,
},
loading_container: {
position: "absolute",
left: 0,
right: 0,
top: 100,
bottom: 0,
alignItems: "center",
paddingTop: 50,
backgroundColor: "white",
},
textinput: {
height: 50,
borderColor: "#999999",
borderWidth: 1,
paddingLeft: 5,
},
});
export default Search;
Using this code as example:
import React, { Component } from 'react';
import { Text, View, FlatList, Dimensions, Button, StyleSheet } from 'react-native';
const { width } = Dimensions.get('window');
const style = {
justifyContent: 'center',
alignItems: 'center',
width: width,
height: 50,
flex: 1,
borderWidth: 1,
};
const COLORS = ['deepskyblue','fuchsia', 'lightblue '];
function getData(number) {
let data = [];
for(var i=0; i<number; ++i)
{
data.push("" + i);
}
return data;
}
class ScrollToExample extends Component {
getItemLayout = (data, index) => (
{ length: 50, offset: 50 * index, index }
)
getColor(index) {
const mod = index%3;
return COLORS[mod];
}
scrollToIndex = () => {
let randomIndex = Math.floor(Math.random(Date.now()) * this.props.data.length);
this.flatListRef.scrollToIndex({animated: true, index: randomIndex});
}
scrollToItem = () => {
let randomIndex = Math.floor(Math.random(Date.now()) * this.props.data.length);
this.flatListRef.scrollToIndex({animated: true, index: "" + randomIndex});
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Button
onPress={this.scrollToIndex}
title="Tap to scrollToIndex"
color="darkblue"
/>
<Button
onPress={this.scrollToItem}
title="Tap to scrollToItem"
color="purple"
/>
</View>
<FlatList
style={{ flex: 1 }}
ref={(ref) => { this.flatListRef = ref; }}
keyExtractor={item => item}
getItemLayout={this.getItemLayout}
initialScrollIndex={50}
initialNumToRender={2}
renderItem={({ item, index}) => (
<View style={{...style, backgroundColor: this.getColor(index)}}>
<Text>{item}</Text>
</View>
)}
{...this.props}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
header: {
paddingTop: 20,
backgroundColor: 'darkturquoise',
alignItems: 'center',
justifyContent: 'center'
}
});
export default class app extends Component {
render() {
return <ScrollToExample
data={getData(100)}
/>
}
}
I tried to add a ref but it doesn't work :
// Components/Search.js
import React from 'react'
import { StyleSheet, View, TextInput, Button, Text, FlatList, ActivityIndicator } from 'react-native'
import FilmItem from './filmItem'
import { getFilmsFromApiWithSearchedText } from '../API/TMDBApi'
class Search extends React.Component {
constructor(props) {
super(props)
this.searchedText = ""
this.state = {
films: [],
isLoading: false,
}
}
_loadFilms() {
{this.scrollToIndex}
if (this.searchedText.length > 0) {
this.setState({isLoading: true})
getFilmsFromApiWithSearchedText(this.searchedText).then(data => {
this.setState({
films: data.results,
isLoading: false
})
})
}
}
_searchTextInputChanged(text) {
this.searchedText = text
}
_displayLoading() {
if (this.state.isLoading) {
return (
<View style={styles.loading_container}>
<ActivityIndicator size='large'/>
</View>
)
}
scrollToIndex = () => {
this.flatListRef.scrollToIndex({index: 1});
}
}
render() {
return (
<View style={styles.main_container}>
<TextInput
style={styles.textinput}
placeholder='Titre du film'
onChangeText={(text) => this._searchTextInputChanged(text)}
onSubmitEditing={() => this._loadFilms()}
/>
<Button title='Rechercher' onPress={() => this._loadFilms()} />
<View>
<FlatList
data={this.state.films}
ref={(ref) => { this.flatListRef = ref; }}
keyExtractor={(item) => item.id.toString()}
onEndReachedThreashold={1}
onEndReached={() => {console.log("TOC")}}
renderItem={({item}) => <FilmItem film={item}/>}
/>
</View>
{this._displayLoading()}
</View>
)
}
}
const styles = StyleSheet.create({
main_container: {
marginTop: 60,
padding: 15,
flex: 1,
},
loading_container: {
position: 'absolute',
left: 0,
right: 0,
top: 100,
bottom: 0,
alignItems: 'center',
paddingTop: 50,
backgroundColor: 'white',
},
textinput: {
height: 50,
borderColor: '#999999',
borderWidth: 1,
paddingLeft: 5,
}
})
export default Search
I'm sur I am doing something wrong, but don't find the error. Thanks a lot for your help.

Is there a way to "fade in" items in flatlist?

I'm setting up a component that render a flatlist and I'm trying to make the flatlist items "fade in" animation For a more impressive display
This is a component for render search suggestions that show items
import React, { Component } from 'react'
import { View, Text, TextInput, FlatList, Image, TouchableOpacity } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { Button } from '../../components'
import Style from './style'
import I18n from '../../i18n'
import Icon from 'react-native-vector-icons/MaterialIcons'
import Api from '../../utils/Api'
import _ from 'lodash'
let mounted = false
#inject('UserStore', 'NavigationStore')
#observer
class SearchProducts extends Component {
constructor(props) {
super(props)
this.state = {
searchAutoComplete: [],
showAutoComplete: false,
currentSearch: '',
searchTimeoutId: null,
}
this.autoCompleteTimeout = null
this.storedResults = []
}
componentWillMount() {
mounted = true
}
componentWillUnmount() {
mounted = false
clearTimeout(this.autoCompleteTimeout)
}
_renderCategory = ({ item }) => {
return (
<View style={Style.featuredView}>
<Image source={item.image} style={Style.featuredImage} />
<Text style={{ textAlign: 'center', color: '#9B999A' }}>{item.title}</Text>
</View>
)
}
_renderSuggestion = ({ item, index }) => {
const splittedName = item.split(' ')
let splittedSearch = this.state.currentSearch.toUpperCase().split(' ')
splittedSearch = splittedSearch.map(x => x.trim()).filter(x => x.length > 1)
let suggestion = []
if (splittedSearch.length == 0) {
suggestion = splittedName.map((word, index) => <Text key={index}>{word} </Text>)
} else {
let highlightedWords = []
splittedName.forEach((word, index) =>
splittedSearch.forEach(wordFromSearch => {
const currentWord = word.toUpperCase()
const isAlreadyHighlighted = highlightedWords.includes(currentWord)
if ((currentWord.includes(wordFromSearch.toUpperCase()) && this.state.currentSearch.length > 0) || isAlreadyHighlighted) {
let v = (
<Text key={index} style={{ color: '#2eb872' }}>
{word}{' '}
</Text>
)
if (!isAlreadyHighlighted) {
highlightedWords.push(currentWord)
}
suggestion[index] = v
} else {
let v = <Text key={index}>{word} </Text>
suggestion[index] = v
}
})
)
}
return (
<TouchableOpacity
style={Style.suggestionView}
onPress={() => {
this.props.UserStore.addRecentSearch(item)
this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: item } })
this.autoCompleteTimeout = setTimeout(() => {
if (mounted) this.setState({ showAutoComplete: false })
}, 400)
}}
>
<Icon name='search' size={20} style={{}} />
<Text style={{ marginLeft: 20, textAlign: 'left', color: '#9B999A' }}>{suggestion}</Text>
</TouchableOpacity>
)
}
getSuggestions = async currentSearch => {
try {
const response = await Api.serachOutoCompleate(currentSearch)
let searchAutoComplete = response.suggestions.products.map(product => product.product_title)
response.suggestions.categories.forEach(categories => searchAutoComplete.push(categories))
response.suggestions.warehouses.forEach(warehouse => searchAutoComplete.push(warehouse.warehouse_name))
response.suggestions.upcs.forEach(upcs => searchAutoComplete.push(upcs.product_title))
response.suggestions.tags.forEach(tags => searchAutoComplete.push(tags.product_title))
this.storedResults[currentSearch] = searchAutoComplete
if (mounted && currentSearch && searchAutoComplete) this.setState({ currentSearch: currentSearch, searchAutoComplete: searchAutoComplete })
else this.setState({ currentSearch: currentSearch })
} catch (error) {
console.log(error)
}
}
_onSearchChange = _.debounce(currentSearch => {
if (currentSearch === '') {
this.setState({ filter: [], currentSearch })
} else {
if (this.storedResults[currentSearch]) {
this.setState({ currentSearch })
let searchAutoComplete = this.storedResults[currentSearch]
if (mounted && currentSearch && searchAutoComplete) this.setState({ searchAutoComplete })
} else {
this.getSuggestions(currentSearch)
}
}
}, 250)
render() {
I18n.locale = this.props.UserStore.user.lang
const recent = this.props.UserStore.RecentSearches
return (
<View style={Style.container}>
<View style={Style.search_container}>
<TextInput
style={Style.search_input}
underlineColorAndroid='transparent'
placeholder={I18n.t('search_products')}
returnKeyType='search'
autoCorrect={false}
onChangeText={this._onSearchChange}
onFocus={() => this.setState({ showAutoComplete: true })}
onSubmitEditing={event => {
if (event.nativeEvent.text.length) this.props.UserStore.addRecentSearch(event.nativeEvent.text)
this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: event.nativeEvent.text } })
}}
onKeyPress={() => this.suggestionTimeout && clearTimeout(this.suggestionTimeout)}
blurOnSubmit
/>
</View>
{this.state.currentSearch.length > 0 && this.state.showAutoComplete && this.state.searchAutoComplete.length > 0 ? (
<View style={{ paddingVertical: 10 }}>
<FlatList initialNumToRender={20} data={this.state.searchAutoComplete} keyExtractor={(item, index) => item.toString()} renderItem={this._renderSuggestion} keyboardShouldPersistTaps='always' />
</View>
) : (
<View>
{recent.length > 0 ? (
<View>
<View style={Style.whiteBorder} />
<View style={Style.searchHistory}>
<Text style={Style.searchHistory_header}>{I18n.t('recent_searches')}</Text>
{recent.map((title, index) => (
<Button
key={index}
style={Style.recentSearch}
onPress={() => {
this.props.UserStore.addRecentSearch(title)
this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: title } })
}}
>
<Icon name='schedule' style={Style.recentSearchIcon} />
<Text style={Style.recentSearchText}>{title}</Text>
</Button>
))}
</View>
</View>
) : null}
</View>
)}
</View>
)
}
}
export default SearchProducts
I expect the output will show fade in animation in the flatlist
and i dont know how to implement it
This can be accomplished by using the Animated api.
First import Animated from react-native, then add fade: new Animated.Value(0) to your state inside the constructor.
Now change the View that is surrounding the FlatList from this
<View style={{ paddingVertical: 10 }}>
to this
<Animated.View style={{ paddingVertical: 10, opacity: this.state.fade }}>
At last add this block to start the animation when the list mounts:
componentDidMount() {
Animated.timing(this.state.fade, {
duration: 500,
toValue: 1,
useNativeDrivers: true
}).start();
}
If you want to animate the FlatList in every time the user makes a search, you would have to move this block to another part of your program logic and remember to set the fade value back to 0 before the animation.

How to highlight search results in React-Native FlatList?

I'm newbie in React-native. I need to highlight the search results in my FlatList while I'm typing in search bar. There are 2 componenrs: react-native-highlight-words and react-native-text-highlight , But I cant figure out how to make use of them!
here is my code:
import React, { Component } from 'react';
import {StyleSheet, Text, View, FlatList, TouchableOpacity } from 'react-native';
import { List, ListItem, SearchBar } from 'react-native-elements';
import DropdownMenu from 'react-native-dropdown-menu';
import {Header, Left, Right, Icon} from 'native-base'
var SQLite = require('react-native-sqlite-storage')
var db = SQLite.openDatabase({name: 'test.sqlite', createFromLocation: '~dictionary.sqlite'})
var data = [["English", "Arabic", "Persian"]];
export default class App extends Component {
constructor(props) {
super(props)
this.state = {record: [], arrayholder : [], query:''};
db.transaction((tx) => {
tx.executeSql('SELECT * FROM tblWord', [], (tx, results) => {
let row = results.rows.item();
arrayholder = results.rows.raw()
record = results.rows.raw()
this.setState({arrayholder: arrayholder})
this.setState({ record: record })
}});});
}
searchFilterFunction = text => {
var newData = this.state.arrayholder;
newData = this.state.arrayholder.filter(item => {
const itemData = item.word_english.toLowerCase()
const textData = text.toLowerCase()
return itemData.indexOf(textData) > -1 });
this.setState({query: text,record: newData });
};
render() {
return (
<View style = {styles.container}>
<Header style={styles.headerStyle}>
...
</Header>
<View style={styles.menuView}>
<DropdownMenu
bgColor={"#B38687"}
activityTintColor={'green'}
titleStyle={{color: '#333333'}}
handler={(selection, row) => this.setState({text4: data[selection][row]})}
data={data}
>
</DropdownMenu>
</View >
<View >
<View style={styles.searchBarView}>
<SearchBar
placeholder="Search"
lightTheme
value = {this.state.query}
onChangeText={text => this.searchFilterFunction(text)}
autoCorrect={false}
inputStyle={{backgroundColor: 'white'}}
containerStyle={{backgroundColor: 'white', borderWidth: 1, borderColor:'#B38687', }}
/>
</View>
<View style={styles.flatListVew}>
<List containerStyle={{ flexDirection: 'column-reverse', borderTopWidth: 0, borderBottomWidth: 0 }} >
<FlatList
data={this.state.record}
keyExtractor={((item, index) => "itemNo-" + index)}
renderItem={({item}) => (
<ListItem
roundAvatar
onPress={() => {this.props.navigation.navigate('Screen2', {data: (item.word_english +'\n' + item.word_arabic)} ); }}
title={item.word_english}
containerStyle={{ borderBottomWidth: 0 }}
/> )}
/>
</List>
</View>
</View>
</View>);}
}
const styles = StyleSheet.create({
...
I want the results to look like this:
Any help would be greatly appreciated.
You can pass text or custom view to ListItem component as props for title. I am using React Native Highlight Words to highlight text as you stated.
add React Native Highlight Words by add the below line:
import Highlighter from 'react-native-highlight-words';
Update code for ListItem component for desired result:
<ListItem
roundAvatar
onPress={() => {this.props.navigation.navigate('Screen2', {data: (item.word_english +'\n' + item.word_arabic)} ); }}
title={
<Highlighter
highlightStyle={{backgroundColor: 'yellow'}}
searchWords={[this.state.query]}
textToHighlight={item.word_english}
/>}
containerStyle={{ borderBottomWidth: 0 }}
/>
You can highlight using your own styles.
Here is a simple example:
const myList = [{ text: 'Hi', id: 1 }, ... ]
class List extends Component {
this.state = { highlightedId: undefined }
render() {
return (
<FlatList
data={myList}
renderItem={({item}) => <Text style={item.id === this.state.highlightedId ? styles.hightlighted : undefined}>{item.text}</Text>}
/>
)
}
}
const styles = StyleSheet.create({
highlighted: {
backgroundColor: "yellow"
}
})
In your case you can adjust the containerStyle of the <ListItem />.
handleChangeText = param => {
const {categoryList} = this.state;
const regEx = "\\s*(" + param + ")\\s*"
const validator = new RegExp(regEx, 'i');
let filterData = [];
//here is categorylist is the data supplied to flatlist.
categoryList.forEach(item => {
let flag = validator.test(item.teamtype);
if (flag) {
//here set the highlighting color
}
})
};
Call the above function onChangeText() of your search field.