Actually i'm working for a school project in react native and i want to know if it's possible to add two buttons into flatlist using react-native.
export class ItineraryScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[
{key: 'PKRX'},
{key: 'UXUA'},
{key: 'PGRF'},
]
};
}
render() {
return (
<ScrollView>
<FlatList
data={this.state.data}
renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
/>
</ScrollView>
);
}
could you give some advices to implement this feature please?
Best regards,
Imad.
Here is an example of how yu could do it (Repro on Snack Expo) :
import * as React from 'react';
import { Text, View, StyleSheet , FlatList, Button} from 'react-native';
export default function App() {
const data = [
{key: 'PKRX'},
{key: 'UXUA'},
{key: 'PGRF'},
];
return (
<View>
<FlatList data={data} renderItem={({item}) => <Item item={item} /> } />
</View>
);
}
const Item = ({item}) => {
return (
<View style={{flex: 1, flexDirection: 'row', alignItems: 'center'}}>
<Text>{item.key}</Text>
<View style={{flex:1, flexDirection: 'row-reverse'}}>
<Butto title='Button 1' onPress={() => {}} />
<Button title='Button 2' onPress={() => {}} />
</View>
</View>
)
}
Related
I am a new in react native i am try to set search bar in my application. To search in flatlist data. i am not able to search in flatlist data ,What is the error i don't know. how can i set how to resolve my problem please resolve my issue. i have attached the my code given below.
import React from 'react';
import { StyleSheet, FlatList, View, TouchableOpacity, Image, Text, TextInput } from 'react-native';
import { dishesData } from './DishesData';
import { SearchBar } from 'react-native-elements'
const MenuListScreen = ({ navigation }) => {
const state = {
searchText: "",
dishesData:[],
filteredData: [],
};
let search = (searchText) => {
this.setState({searchText: searchText});
let filteredData = state.dishesData.filter(function (item) {
return item.description.includes(searchText);
});
this.setState({filteredData: filteredData});
};
return (
<View style={styles.container}>
<SearchBar
round={true}
lightTheme={true}
placeholder="Search..."
autoCapitalize='none'
autoCorrect={false}
onChangeText={search}
value={state.searchText}
/>
<FlatList style={styles.list}
contentContainerStyle={styles.listContainer}
data={dishesData}
horizontal={false}
numColumns={1}
keyExtractor={(item) => {
return item.id;
}}
renderItem={({ item }) => {
return (
<TouchableOpacity
onPress={() => navigation.navigate('MenuDetail', { id: item.id })}
>
<Image
style={styles.userImage}
source={{ uri: item.imageSource }}
/>
<View style={styles.cardFooter}>
<View style={{ alignItems: "center", justifyContent: "center" }}>
<Text style={styles.name}>{item.title}</Text>
<Text style={styles.position}>{item.price}</Text>
{/* <TouchableOpacity style={styles.followButton}
onPress={() =>
props.navigation.navigate('DetailsPage', item)
}>
<Text style={styles.followButtonText}>Buy Now</Text>
</TouchableOpacity> */}
</View>
</View>
</TouchableOpacity>
)
}} />
</View>
);
};
Hi there you can filter items by using filter function and you are already doing that but for accuracy I'll suggest to do like this.
let search = (searchText) => {
this.setState({searchText: searchText});
let filteredData = state.dishesData.filter(function (item) {
return item.description.toUpperCase().includes(searchText.toUpperCase());
});
this.setState({filteredData: filteredData});
};
and to render the filtered items on Flatlist you have to toggle data array on FlatList
<FlatList style={styles.list}
contentContainerStyle={styles.listContainer}
data={state.searchText ? state.filteredData:state.dishesData}
horizontal={false}
numColumns={1}
keyExtractor={(item) => {
return item.id;
}}.../>
Here is the Snack Link you can test as well Working Example
Can anyone tell me how to solve these things?
1.if the list is pressed, I'd like to change the background color of the list
beige(#FFF5E7) to white(#FBFBFB)
2.Also, I'd like to change the read value of the Object fales to true with useState
Problem is that if I pressed the list, whole background color of the list will be changed.
index.tsx
import React, { useState } from 'react';
import { Text, View, TouchableOpacity, FlatList } from 'react-native';
import { useNavigation } from '#react-navigation/native';
import { DETAIL } from '../../sample';
import { Object } from './sample';
export default function sample() {
const [state, setState] = useState(Object);
const navigation = useNavigation();
let Element;
const renderItem = ({ item }) => {
const readState = () => {
navigation.navigate(NOTICE_DETAIL);
const readValue = [...state];
let value = { ...readValue[0] };
value.read = true;
readValue[0] = value;
setState(readValue);
};
if (state[0].read) {
Element = (
<TouchableOpacity onPress={readState}>
<View style={[styles.row, { backgroundColor: '#FBFBFB' }]}>
<View style={styles.container}>
<View style={styles.end}>
<Text style={styles.text}>{item.text}</Text>
<Text style={styles.time}>{item.time}</Text>
</View>
<Text style={styles.content}>{item.content}</Text>
</View>
</View>
</TouchableOpacity>
);
} else {
Element = (
<TouchableOpacity onPress={readState}>
<View style={[styles.row, { backgroundColor: '#FFF5E7' }]}>
<View style={styles.container}>
<View style={styles.end}>
<Text style={styles.text}>{item.text}</Text>
<Text style={styles.time}>{item.time}</Text>
</View>
<Text style={styles.content}>{item.content}</Text>
</View>
</View>
</TouchableOpacity>
);
}
return Element;
};
}
return (
<View style={{ flex: 1 }}>
<FlatList
extraData={Object}
data={Object}
renderItem={renderItem}
/>
</View>
);
}
Object.ts
export const Object = [
{
id: 1,
text: 'testtesttest',
content: 'testtesttest'
read: false
},
{
id: 2,
text: 'testtesttest',
content: 'testtesttest'
read: false
}
id: 3,
text: 'testtesttest',
content: 'testtesttest'
read: false
}
]
We can add inline styles into the component style props along with static styles,
For Example:
<TouchableOpacity onPress={readState}>
<View style={[styles.row, { backgroundColor: item.read ? '#FBFBFB' : 'FFF5E7' }]}>
<View style={styles.container}>
<View style={styles.end}>
<Text style={styles.text}>{item.text}</Text>
<Text style={styles.time}>{item.time}</Text>
</View>
<Text style={styles.content}>{item.content}</Text>
</View>
</View>
</TouchableOpacity>
Problem in your readState function and if (state[0].read) {. You always change item with index 0 and then check state[0].read for all elements of your array.
I am using react native. Now, when I try to center the flatlist in the center of the screen with either specifically giving the flatlist with justifyContent and alignItems, it gives me a weird action. Also, contentContainerStyle with justifyContent and alignItems as center also gives an weird action. Been searching all day yestarday for solution. I will provide code and image below. Thank you.
im trying to align this flatlist in the center just like justfyContent and alignItems would do. You can see that the content leans towards the left of the screen.
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
import PokeDetails from "./PokeDetails";
import SearchBarComponent from "../components/SearchBar";
import PokeBanner from "../components/PokeBanner";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response.results,
})
console.log("RESPONSE",response)
console.log("RESPONSE.RESSSULTS",response.results)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={GlobalStyles.container}>
<SearchBarComponent style={GlobalStyles.searchBar}/>
<PokeBanner/>
<View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
<View style={GlobalStyles.pokeFlatList}>
<FlatList
contentContainerStyle={{flexDirection: "row",justifyContent:"center", alignItems:"center"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
</View>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
This is what happens when I try to add contentContainerStyle using the code below
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
import PokeDetails from "./PokeDetails";
import SearchBarComponent from "../components/SearchBar";
import PokeBanner from "../components/PokeBanner";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response.results,
})
console.log("RESPONSE",response)
console.log("RESPONSE.RESSSULTS",response.results)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={GlobalStyles.container}>
<SearchBarComponent style={GlobalStyles.searchBar}/>
<PokeBanner/>
<View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
<View style={GlobalStyles.pokeFlatList}>
<FlatList
contentContainerStyle={{justifyContent:"center", alignItems:"center"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
</View>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
For this you can use FlatList columnWrapperStyle and remove flex:1 from your View
change:
<FlatList
contentContainerStyle={{justifyContent:"center", alignItems:"center"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
to
<FlatList
columnWrapperStyle={{ flex: 1,justifyContent: "space-around"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{ flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
Hope this helps!
The only thing you have to do is change the style of renderItem of FlatList from,
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
to
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', margin: 1 }}>
also remove your contentContainerStyle from FlatList.
For more information check below working example (remove some code to make a minimum working example)
import React from "react";
import { View, FlatList, Image, Text } from "react-native";
export default class Home extends React.Component {
state = {
isLoading: true,
dataSource: [],
};
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
.then((res) => res.json())
.then((response) => {
this.setState({
isLoading: false,
dataSource: response.results,
});
});
}
render() {
return (
<View>
<FlatList
data={this.state.dataSource}
keyExtractor={(item) => item.name}
numColumns={3}
renderItem={({ item }) =>
<View style={{flex: 1, justifyContent: "center", alignItems: "center", margin: 1}}>
<Image
source={{uri: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`}}
style={{ width: 75, height: 75 }}
/>
<Text>{item.name}</Text>
</View>
}
/>
</View>
);
}
}
Hope this helps you. Feel free for doubts.
My ReactNative FlatList is not rendering with this simple implementation.
<FlatList style={{flex:1, backgroundColor:'red'}}
data = {this.state.users}
keyExtractor={item => item.key.toString()}
renderItem={({item}) => {
return (
<ChatUserCard key={item.uid} username={item.username} />
)
}}
/>
ChatUserCard
<View style={styles.cardStyle}>
<Text style={styles.itemStyle}>{this.props.username}</Text>
<Button style={styles.buttonStyle}
title='Chat'
onPress={this.startChat} />
</View>
Try add comments to the view below the flatlist and remove flex 1 from the styles on the flatlist. Try that to check if it is related with the styles
I'm thinking what's going on is that you've not wrapped your FlatList in a View that has flex: 1 set. Also, you can probably use your uid as your key, rather than setting a key in your object data
Demo
https://snack.expo.io/#anonymoussb/so53688423
import * as React from 'react';
import { Text, View, StyleSheet, Button, FlatList } from 'react-native';
class ChatUserCard extends React.Component {
render() {
return (
<View style={styles.cardStyle}>
<Text style={styles.itemStyle}>{this.props.username}</Text>
<Button style={styles.buttonStyle}
title='Chat'
onPress={this.startChat} />
</View>
)
}
}
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [
{ key: 123, uid: 123, username: 'taco' },
{ key: 456, uid: 456, username: 'cat' }
]
}
}
render() {
return (
<View style={styles.container}>
<FlatList style={{flex:1, backgroundColor:'red'}}
data = {this.state.users}
keyExtractor={item => item.key.toString()}
renderItem={({item}) => {
return (
<ChatUserCard key={item.uid} username={item.username} />
)
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
Works:
<FlatList
data={['0', '1', '2', '3', '4']}
renderItem={({ item }) => (
<Button title={item} />
)}
/>
Doesn't work (nothing rendered):
<FlatList
data={[...Array(5).keys()].map(String)}
renderItem={({ item }) => (
<Button title={item} />
)}
/>
What could possibly be the cause?
Its actually working, check out the demo below
https://snack.expo.io/H1elODwPb
And the code
import React, { Component } from 'react';
import { View, StyleSheet,FlatList,Button } from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<FlatList
data={[...Array(5).keys()].map(String)}
renderItem={({ item }) => (
<Button title={item} />
)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ecf0f1',
},
});