Create rows in React Native - javascript

i want to create rows for images,which recieve from _find function.This function already seperated array to subarrays,which number equals number of rows,how i can render rows with data from _find?Dont purpose ready solutions such as react-native-easy-grid,i want to do it without another libs,and can i scroll items if i use this way?
import React, { Component } from 'react';
import { AppRegistry, Text, TextInput, View,StyleSheet,Button,Image,ScrollView,Dimensions,ListView } from 'react-native';
import Grid from './GridBuilder.js';
const regUrl = /(src=")?(https:\/\/\S{2,500})(")/gm;
var IMAGES_PER_ROW = 3;
let app1;
export default class inputText extends Component {
constructor(props) {
super(props);
app1 = this;
this.state = {
text: null,
findEvent:false,
im_p_r:3,
items:{},
};
}
render() {
return (
<View style={{margin: 20}}>
<TextInput
style = {styles.searchInput}
placeholder="Type here to search"
onChangeText={(text) => this.setState({text})}
/>
<Button
onPress={() => this._find(this.state.text)}s
title='Find'
color="#841584"
accessibilityLabel="on"
/>
{this.state.findEvent && <DisplayImage />}
</View>
);
}
_find(searchText){
fetch('https://www.googleapis.com/customsearch/v1?key=AIzaSyAfcN3jfimFxHxpHNjhHOSuuY8dm5YZnqQ&cx=007223195539364418542:lcqjo0djp7k&num=10&q='+ searchText+'&searchType=image')
.then((resp) => resp.json())
.then(function(data) {
let s = data.items;
let SIZE = IMAGES_PER_ROW;
let res = s.reduce((p,c)=>{
if(p[p.length-1].length == SIZE){
p.link.push([]);
}
p[p.length-1].push(c);
return p.link;
}, [[]])
app1.setState({items:res,findEvent:true});
})
}
}
export class DisplayImage extends Component {
render(){
return(
<View style={styles.container}>
{app1.state.items.map((item,index) => <View style={styles.row} ><Image style={[styles.image,styles.box]} source={{uri:item.link}} key={index} /></View>)}
</View>
)
}
}
const styles = StyleSheet.create({
searchInput:{
fontSize:20,
paddingTop:20,
paddingBottom:20
},
image:{
paddingTop:20,
width:100,
height:100,
},
row: {
flex: 1,
flexWrap: 'wrap',
flexDirection: 'row',
justifyContent: 'space-between'
},
box: {
flex: 1,
height: 100,
width:100,
backgroundColor: '#333',
},
})
AppRegistry.registerComponent('inputText', () => inputText);
AppRegistry.registerComponent('DisplayImage', () => DisplayImage);

You can use FlatList from React Native.
{this.state.findEvent && <FlatList
data={this.state.items}
renderItem={({ item }) => this.renderItem(item)}
/>}
FlatList receive as data the list of elements you want to render, in this case the data returned from the find function.
And then define the renderItem function like:
renderItem(item) {
return (
<View style={styles.row} >
<Image
style={[styles.image,styles.box]}
source={{uri:item.link}} key={index}
/>
</View>
);
}
This function is in charge of rendering the list of images, each image as a row as you want.
FlatList is really useful and makes lists rendering easier. You get the scroll by default and you can also render separators, have a pull to refresh, etc. Take a look to the FlatList doc to see all properties available.

Here is working example of Flat list by which you can get images in the row
https://snack.expo.io/SJDoljDg7

FlatList is the way to go but I suspect the spec has changed since the original accepted answer. You must now provide a key extractor, here is an example of what worked for me:
const listItems = [
{
"id": 0.7967679550647925,
"name": "Hcsrhjkh",
},
{
"id": 0.3212834674770011,
"name": "Phvdgbb",
},
{
"id": 0.30092504022778455,
"name": "Hnvdghbh",
},
]
...
{listItems.length < 1 ? (
<Text style={{ fontSize: 30 }}>Your list is empty.</Text>
) : (
<FlatList
data={listItems}
renderItem={({item}) => <ListItem item={item} />}
keyExtractor={(item) => item.id.toString()}
/>
)}
As you can might have found, the keyExtractor expects a string so I've coerced the 'id' which is a number to a string.

Related

React Native how do I make a Search Bar for a Flatlist?

I have been trying to create a search bar all day. I finally found this guide which seemed ok: https://blog.jscrambler.com/add-a-search-bar-using-hooks-and-flatlist-in-react-native/. I followed it through using my own API and I am not getting any errors exactly, but the code in this tutorial seems unfinished.
Here is what I have:
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, SafeAreaView, TextInput } from 'react-native';
import { Card, Header } from 'react-native-elements'
import { styles } from './styles.js';
import filter from 'lodash.filter';
const FormsScreen = ({navigation, route}) => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
const [query, setQuery] = useState('');
const [fullData, setFullData] = useState([]);
//Fetch all users from database
useEffect(() =>{
setIsLoading(true);
fetch('http://10.0.2.2:5000/forms').then(response =>{
if(response.ok){
return response.json();
}
}).then(data => setFullData(data)).then(setIsLoading(false));
}, []);
function renderHeader() {
return (
<View
style={{
backgroundColor: '#fff',
padding: 10,
marginVertical: 10,
borderRadius: 20
}}
>
<TextInput
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="always"
value={query}
onChangeText={queryText => handleSearch(queryText)}
placeholder="Search"
style={{ backgroundColor: '#fff', paddingHorizontal: 20 }}
/>
</View>
);
}
const handleSearch = text => {
const formattedQuery = text.toLowerCase();
const filteredData = filter(fullData, form => {
return contains(form, formattedQuery);
});
setData(filteredData);
setQuery(text);
};
const contains = ({ ID }, query) => {
console.log("ID was: "+ID);
console.log("Query was: "+query);
const id = ID;
console.log('id was: '+id);
if (id.toString().includes(query)) {
return true;
}
return false;
};
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
else{
return (
<SafeAreaView>
<Header
leftComponent={{ icon: 'menu', color: '#fff' }}
centerComponent={{ text: 'Request Forms', style: { color: '#fff', fontSize: 25} }}
rightComponent={{ icon: 'home', color: '#fff' }}
/>
<FlatList
ListHeaderComponent={renderHeader}
keyExtractor={(item) => item.ID.toString() }
data={fullData}
renderItem={({item}) => (
<Card>
<Card.Title>{item.ID}</Card.Title>
<Card.Divider/>
<View style={styles.Container}>
<Text>{item.Comments}</Text>
{/* <Image source={require('./System apps/Media Manager/Gallery/AppPhotos/45e5cefd-7798-4fe9-88de-86a0a15b7b9f.jpg')} /> */}
<Text>{item.RoadName}</Text>
</View>
<View style={styles.ListContainer}>
<Text style={styles.LabelText}>Name</Text>
<Text style={styles.LabelText}>Phone</Text>
<Text style={styles.LabelText}>Email</Text>
</View>
<View style={styles.ListContainer}>
<Text style={styles.CardText}>{item.Name}</Text>
<Text style={styles.CardText}>{item.Phone}</Text>
<Text style={styles.CardText}>{item.Email}</Text>
</View>
</Card>
)}
/>
</SafeAreaView>
);
}
}
export default FormsScreen;
I have 2 main problems here.
1.) The tutorial had me initialize data and setData. setData is called and it looks to me like that is the final result after the search. The problem is that the author never actually used the variable data so I what do I do with it? Right now the the list is unaltered no matter what happens.
2.) I know he is using a different API so instead of filtering through First name, Last name, and Email I am only searching through ID. In this section of the tutorial:
const contains = ({ name, email }, query) => {
const { first, last } = name;
if (first.includes(query) || last.includes(query) || email.includes(query)) {
return true;
}
return false;
};
How does this code relate first and last to the first and last name values in the data? When I use this code but substitute name with ID and therefor first with id the value of query is correct (19 for example) but the value of ID is 2040 which is not the value I am looking for, but 2040 is the last ID in the database, or in other words the most recently entered row.
This is a sample of my data for reference:
Any help is greatly appreciated.
Please update
data={fullData}
to
data={query ? data : fullData} in flat list props. That should display your filtered data whenever search query updated.

Share state between components

I am working on a hobby gym management app, and I am puzzled by the mechanism of sharing state between three components in React-Native.
My three components are:
1. Schedule:
[...]
function Schedule() {
return (
<Stack.Navigator
initialRouteName="Monday"
screenOptions={{
headerStyle: { backgroundColor: "#f58220" },
headerTintColor: "#fff",
headerTitleStyle: { fontWeight: "bold" },
headerRight: () => <SwitchButton />,
}}
>
<Stack.Screen
name="TabStack"
component={TabStack}
options={{ title: "Aerobic Schedule" }}
/>
</Stack.Navigator>
);
}
export default Schedule;
I want the SwitchButton button in my Schedule component (1.) to alternate between DATA_AEROBIC and DATA_KIDS arrays props of the FlatList in (2.) based on the content of the listAerobic boolean variable.
2. MondayPage:
[...]
const MondayPage = () => {
const [selectedId, setSelectedId] = useState(null);
const [listAerobic, setListAerobic] = useState(true);
const renderItem = ({ item }) => {
const backgroundColor = item.id === selectedId ? "#6e3b6e" : "#f9c2ff";
return (
<Item
item={item}
onPress={() => setSelectedId(item.id)}
style={{ backgroundColor }}
/>
);
};
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, padding: 5 }}>
<SafeAreaView style={styles.container}>
<FlatList
data={listAerobic ? DATA_AEROBIC : DATA_KIDS}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
/>
</SafeAreaView>
</View>
</SafeAreaView>
);
};
However, I don't know how to link the listAerobic boolean variable to the state of the SwitchButton component (3.) , and how to make it toggle on and off.
3. SwitchButton:
const SwitchButton = () => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<View style={styles.container}>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
<Text> aerobic/kids</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
marginRight: 5,
padding: 5,
}
});
export default SwitchButton;
Any guidance would be awesome! I mention I have really tried to look it up on different tutorials, but I can't seem to get the gist of it. It is my first project in React/React-Native.
Many thanks!
I think you just need 'value' to accept a prop passed into it on the switch button. Then wherever you use switch button just pass a boolean value into it from state e.g.
<SwitchButton enabled={this.state.switchEnabled}/>
As for setting state 'globally' so this.state.switchEnabled can be updated from various places / accessible all over the app you need to look into state management tools like Redux (or I hear 'React Hooks' is now a thing and preferred....)

Reset state after unmount screen - Hooks?

After getting data from API I set it to state, and render items in Flatlist,
when I select any item from it I manipulate data and add a new property to item object named as "toggle: true"
and it's works well when I select any item from list I add a border based on toggle,
But when I go back to previous screen then re open the lists screen I can see the border rendered around the items, although I reset the state when the unmounted screen
So what's the wrong I made here?
Code snippet
Data
export default {
...
services: [
{
id: 0,
name: 'nameS0',
logo:
'https://cdn2.iconfinder.com/data/icons/hotel-98/64/hair-dryer-tools-beauty-hairdressing-512.png',
price: 19.99,
},
],
employees: [
{
id: 0,
name: 'name0',
img:
'https://www.visualelementmedia.com/wp-content/uploads/2015/04/person-4-400x629.jpg',
},
...
],
};
const VendorProfile = ({navigation}) => {
const [services, setServices] = React.useState(null);
const [employees, setEmployees] = React.useState(null);
const [serviceSelected, setServiceSelected] = React.useState(null);
const [employeeSelected, setEmployeeSelected] = React.useState(null);
// For selected Item (services, employees)
const itemSelected = (data, id) => {
const updated = data.map((item) => {
item.toggle = false;
if (item.id === id) {
item.toggle = true;
data === services
? setServiceSelected(item)
: setEmployeeSelected(item);
}
return item;
});
data === services ? setServices(updated) : setEmployees(updated);
};
...
const renderEmployees = ({item}) => {
return (
<TouchableOpacity
onPress={() => itemSelected(employees, item.id)}
delayPressIn={0}
style={styles.employeeContainer}>
<EmployeePattern style={{alignSelf: 'center'}} />
<View style={styles.employeeLogo}>
<Image
source={{uri: item.img}}
style={[styles.imgStyle, {borderRadius: 25}]}
/>
</View>
<View style={{marginTop: 30}}>
<Text style={{textAlign: 'center'}}> {item.name}</Text>
</View>
<View style={{marginTop: 10, alignSelf: 'center'}}>
{item.toggle && <AntDesign name="check" size={25} color="#000" />} // here it's stuck after back and reopen the screen
</View>
</TouchableOpacity>
);
};
React.useEffect(() => {
setServices(VendorProfileData.services);
setEmployees(VendorProfileData.employees);
() => {
setServices(null);
setEmployees(null);
};
}, []);
return (
<View style={styles.container}>
<FlatList
data={services}
renderItem={renderServices}
horizontal
keyExtractor={(item) => item.id.toString()}
contentContainerStyle={{
justifyContent: 'space-between',
flexGrow: 1,
}}
/>
.....
</View>
);
};
Ok so after trying multiple times, i got it
change this
const updated = data.map((item) => {
to this
const updated = data.map((old) => {
let item = {...old};
and please make sure everything is working and we didn't break a thing :),
On your ItemSelected function you are passing the whole employees list, and going through it now thats fine, but when you changing one item inside this list without "recreating it" the reference to that item is still the same "because its an object" meaning that we are modifying the original item, and since we are doing so, the item keeps its old reference, best way to avoid that is to recreate the object,
hope this gives you an idea.

React-Native for loop using FlatList is giving error

I am new in programming. I would like to render list dynamically. The parent component Navbar has state with Food Type category like Mexican, Chinese. Each of the FoodTypes have their respective Menu
What I like is to render first FoodType and then its respective Menu in FlatList. The data is saved in Navbar Component. I can render the FoodType using FlatList, but problem is in for loop logic.The for loop is giving me error.
Please see the sandbox:
https://codesandbox.io/s/hungry-lamarr-p8mq3
The relevant code is below(line 130-154), in Menu Component
render() {
return (
<View className="container-fluid">
<Text> Here use Flatlist</Text>
for (let i = 0; i < this.props.Objs_Type.length; i++) {
<FlatList
data={this.props.Objs_Type}
renderItem={({item})=>
<Text>{item.FoodType[i]}</Text>
<Text>{item.Menu[i]}</Text>
}
keyExtractor={(item,index)=>item.id}
/>
};
</View>
)
}
use nested flat list one vertical and horizontal flatlist to get the ui
check below code
snack: https://snack.expo.io/#ashwith00/list
code:
import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
const data = [
{
title: 'Chinese',
data: [1, 2, 3, 4],
},
{
title: 'Mexican',
data: [1, 2, 3, 4],
},
{
title: 'Indian',
data: [1, 2, 3, 4],
},
{
title: 'Indian',
data: [1, 2, 3, 4],
},
];
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const renderCategory = ({ item }) => (
<View style={{ alignSelf: 'stretch', height: 200, marginBottom: 20 }}>
<Text>{item.title}</Text>
<FlatList
keyExtractor={(_, i) => i.toString()}
data={item.data}
horizontal
renderItem={renderBar}
showsHorizontalScrollIndicator={false}
/>
</View>
);
const renderBar = ({ item }) => (
<View
style={{
height: '100%',
width: 240,
backgroundColor: 'red',
marginRight: 10,
}}
/>
);
return (
<View style={styles.container}>
<FlatList
showsVerticalScrollIndicator={false}
data={data}
keyExtractor={(_, i) => i.toString()}
renderItem={renderCategory}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
You need to change your render() function in this way:
render() {
return (
<View className="container-fluid">
<Text> Here use Flatlist</Text>
<FlatList
data={this.props.Objs_Type}
renderItem={({ item }) => (
<View>
<Text>{item.FoodType}</Text>
<Text>{item.Menu}</Text>
</View>
)}
keyExtractor={(item, index) => item.id}
/>
</View>
)
}
The error which I saw in the sandbox link you provided is "Unexpected token". Whenever you get this error, it is most likely due to a syntactic mistake. In your case, it was missing curly braces around your for-loop. Remember whenever you embed any JavaScript code into a JSX block, make sure you encapsulate the JavaScript codes within curly braces.
return (
<jsx-code>
{
some-js-logic like if-else, etc.
}
</jsx-code>
)
Now in your case, even if you add a pair of braces, it won't work, because the for loop in JSX won't work that way. More on this in the first link which I provided at the end.
And to solve your problem, you don't have to use a for-loop at all. The FlatList component accepts the array in its data param. So you don't have to loop through the array. All you got to do is use the items of this array to render your own UI. Here's a sample which is the simplest representation of your code snippet.
render() {
return (
<View className="container-fluid">
<Text> Here use Flatlist </Text>
{
this.generateFlatList(this.props.Objs_Type)
}
</View>
);
}
generateFlatList(objsTypes) {
console.log(objsTypes);
return (
<FlatList
data={objsTypes}
renderItem={({item}) => <Text>{item.FoodType}</Text>}
keyExtractor={(item) => item.id}
/>
);
}
Here are some links which might help you learn more about using for-loop in React JSX and FlatList component:
https://flaviocopes.com/react-how-to-loop/
https://reactnative.dev/docs/flatlist
Thanks all for the valuable comments. Helped me learned alot. If someone is interested, below is the corrected code
<View className="container-fluid">
<Text> Here use Flatlist</Text>
<FlatList
data={this.props.Objs_Type}
renderItem={({ item }) => (
<React.Fragment>
<Text>{item.FoodType}</Text>
{item.Menu.map(e => (
<Text>{e}</Text>
))}
</React.Fragment>
)}
keyExtractor={item => item.id}
/>
</View>
renderItem if you put two tags like two Texts, it will iterate it automatially. So in my case, i had two items in Food_Type and 3 Menu items in each of Food_Type. if you just use two Text each for Food_Type and Menu, it will first print Chinese, then the array ofMenu of Chinese. To display Menu vertically i had to use map .

React native flatlist, not expected behavior

Hi I am starting to use FlatList component instead of ListView and I am having some problems trying to render the separator, I made a multiple-choice component and it is working ok but I don't understand why it is not rendering the separator from the flatlist, if I put the separator inside the renderItem function it's working ok, but I want to use it from the flatlist as a prop.
One curious thing is if I delete the itemSeparatorComponent prop from the FlatList in render method the component stops updating the checkmark (renderIndicator()) that indicates that item is selected, so it's really annoying this, I put the whole code, please check it.
React native: 0.44.0
import React, { Component } from 'react';
import { Button, Icon, Divider } from 'react-native-elements';
import { FlatList, View, TouchableOpacity, Text } from 'react-native';
import { Card, CardSection } from './commons';
import { appMainColor } from '../constants';
export default class ListOrderItems extends Component {
static navigationOptions = {
title: 'Realice su selección'
};
state = { selected: [], items: this.props.navigation.state.params.items };
onItemPress = (item) => {
const selected = this.state.selected;
const index = selected.indexOf(item.name);
if (index === -1) {
selected.push(item.name);
} else {
selected.splice(index, 1);
}
this.setState({ selected });
};
isSelected = (item) => {
return this.state.selected.indexOf(item.name) !== -1;
};
keyExtractor = (item, index) => {
return index;
};
renderOkButton = () => {
if (this.props.navigation.state.params.type === 'multipleChoice') {
return (
<Button
raised
borderRadius={5}
backgroundColor={appMainColor}
title='Aceptar'
onPress={() => this.props.navigation.goBack()}
/>
);
}
};
renderCancelButton = () => {
return (
<Button
raised
borderRadius={5}
backgroundColor={appMainColor}
title='Cancelar'
onPress={() => this.props.navigation.goBack()}
/>
);
};
renderIndicator = (item) => {
if (this.isSelected(item)) {
return <Icon name="check-circle" color={appMainColor} />;
}
};
renderSeparator = () => {
return <Divider />;
};
renderItem = ({ item, index }) => {
return (
<TouchableOpacity
activeOpacity={0.7}
onPress={() => this.onItemPress(item, index)}
>
<View style={styles.row}>
<View style={styles.optionLabel}>
<Text>{item.name} (${item.price})</Text>
</View>
<View style={styles.optionIndicator}>
{this.renderIndicator(item, index)}
</View>
</View>
</TouchableOpacity>
);
};
render() {
return (
<View>
<Card>
<CardSection>
<FlatList
data={this.state.items}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
itemSeparatorComponent={() => this.renderSeparator()}
/>
</CardSection>
</Card>
<Card>
<CardSection style={{ justifyContent: 'space-around' }}>
{this.renderOkButton()}
{this.renderCancelButton()}
</CardSection>
</Card>
</View>
);
}
}
const styles = {
row: {
flexDirection: 'row',
padding: 5
},
optionLabel: {
flex: 1,
},
optionIndicator: {
width: 30,
height: 30,
justifyContent: 'center',
alignItems: 'center'
}
};
I think you made some typo, it should be ItemSeparatorComponent, not itemSeparatorComponent.
Flatlist list items are pure components if you want to check with are selected you should set this in the data source you pass in. Otherwise, the props for the item remain the same and the component will not rerender.
For the divider can you try itemSeparatorComponent={Divider}

Categories