New to react native. I have a simple component that takes in a list of ingredients and returns the items in a flatList of text. For some reason I can't get the data to render. Am I doing something wrong?
My ingredients looks like this:
const ingredients = [chicken, butter, oil]
const DisplayRec = ({ ingredients }) => {
return (
<View style={styles.container}>
<Text>Your Recipes</Text>
<FlatList
//keyExtractor={(recName) => recName}
data={ingredients}
renderItem={({ recName }) => (
<Text>{recName}</Text>
)}
/>
</View>
);
};
You are using it in incorrect manner
please try
<FlatList
//keyExtractor={(recName) => recName}
data={ingredients}
renderItem={({item, index}) => (
<Text>{item}</Text>
)}
/>
also please go throught the documentation of FlatList
https://reactnative.dev/docs/flatlist#required-renderitem
First you have to go through with the official documentation of
React-native .
flatlist documentation
you can just simply pass ingredients data to flatlist and render its
function
For live editing expo link
const ingredients = [
{
id: 'bd7',
title: 'chicken',
},
{
id: '3ac',
title: 'butter',
},
{
id: '5869',
title: 'oil',
},
];
export default function App() {
const renderItem = ({ item }) => (
<Text>{item.title}</Text>
);
return (
<View >
<FlatList
data={ingredients}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</View>
);
}
you need to use return in render item
<FlatList
//keyExtractor={(recName) => recName}
data={ingredients}
renderItem={({ recName }) => {
return (
<Text>{recName}</Text>
)}}
/>
Hope it's working fine for you
Related
i'm currently trying to implement a horizontal FlatList. I'm aware that i can render list of items pretty easly inside the renderItem by just looping it through... but can i actually pass a custom component inside ?
This is my array filled with custom components i created:
const arrayOfCustomComponents = [<Home/>,<News/>,<History/>,<Stats/>,<Settings />];
Given this array, can i pass each index inside renderItem to be rendered ?
<Animated.FlatList
data={data}
keyExtractor={item => item.key}
horizontal
showsHorizontalScrollIndicator={false}
pagingEnabled
bounces={false}
renderItem={({item}) =>{
return <View>
{arrayOfCustomComponents[item.key]}
</View>
}}
/>
You cannot access an array elements like you've done in your example. The keys of an array are 0, 1, 2, ....
What you can do instead is to store your components in an object like that:
const DATA = [
{
id: 'comp1',
description: 'This is component 1',
},
{
id: 'comp2',
description: 'This is component 2',
}
];
const Comp1 = () => {
return (
<View><Text>This is component 1</Text></View>
)
}
const Comp2 = () => {
return (
<View><Text>This is component 2</Text></View>
)
}
const mapOfComponents = {
comp1: <Comp1 />,
comp2: <Comp2 />
};
function App() {
return (
<View>
<FlatList
data={DATA}
renderItem={({ item }) => {
return (
mapOfComponents[item.id]
)
}
}
keyExtractor={item => item.id}
/>
</View>
);
}
Please! Can somebody explain me whats wrong with following code. I'm trying to pass ListItem
export const ListItem: ListRenderItem<IUser> = ({item}) => {
return (
<RNEListItem onPress={() => {}}>
<Avatar source={{uri: item.picture.thumbnail}} rounded size="medium" />
<RNEListItem.Content>
<RNEListItem.Title>{`${item.name.first} ${item.name.last}`}</RNEListItem.Title>
<RNEListItem.Subtitle>{item.email}</RNEListItem.Subtitle>
</RNEListItem.Content>
<RNEListItem.Chevron size={30} />
</RNEListItem>
);
};
to renderItem prop in FlatList
return (
<FlatList
data={users}
renderItem={ListItem}
ItemSeparatorComponent={ListItemSeparator}
keyExtractor={keyExtractor}
showsVerticalScrollIndicator={false}
ListFooterComponent={ListLoader}
onEndReached={handleMore}
onEndReachedThreshold={0.1}
onRefresh={handleRefresh}
refreshing={isRefreshing}
/>
);
everything fine. But when I'm trying to use hooks
export const ListItem: ListRenderItem<IUser> = ({item}) => {
const {navigate} = useNavigation<RootStackParamList>();
const handlePress = useCallback(() => {
console.log(item.login.uuid);
navigate(ERootStackScreens.USER_SCREEN, {id: item.login.uuid});
}, []);
return (
<RNEListItem onPress={() => {}}>
<Avatar source={{uri: item.picture.thumbnail}} rounded size="medium" />
<RNEListItem.Content>
<RNEListItem.Title>{`${item.name.first} ${item.name.last}`}</RNEListItem.Title>
<RNEListItem.Subtitle>{item.email}</RNEListItem.Subtitle>
</RNEListItem.Content>
<RNEListItem.Chevron size={30} />
</RNEListItem>
);
};
RN return's
Hooks can only be called inside the body of a function component.
but when i change renderItem this way
return (
<FlatList
data={users}
renderItem={()=>ListItem}
ItemSeparatorComponent={ListItemSeparator}
keyExtractor={keyExtractor}
showsVerticalScrollIndicator={false}
ListFooterComponent={ListLoader}
onEndReached={handleMore}
onEndReachedThreshold={0.1}
onRefresh={handleRefresh}
refreshing={isRefreshing}
/>
);
Everything becomes fine. But it looks like types in docs are incorrect. Cuz according to them first example should work without problems
renderItem: ListRenderItem<ItemT> | null | undefined;
export type ListRenderItem<ItemT> = (info: ListRenderItemInfo<ItemT>) => React.ReactElement | null;
You need to pass the props in the functional component:
renderItem={(props)=><ListItem {...props} />}
So basically what I said in the title, I am simply trying to change a prop that im passing to the component of Post if the item currently being rendered is in the viewport.
I am getting double the output like its firing twice, and its not even correct.
im comparing a key to the id (same thing) and if the 'activeVideo !== item.id' (video id's) are the same
the video should play, because i pass 'False' to the 'paused' property.
question is why am i getting double the output and why are both videos being paused when one of them clearly shouldnt>?
Need help fast, its for a school project.
Home.js
const [activeVideo, setActiveVideo] = useState(null);
const onViewRef = React.useRef((viewableItems)=> {
setActiveVideo(viewableItems.changed[0].key)
})
const viewConfigRef = React.useRef({ viewAreaCoveragePercentThreshold: 75 })
return (
<View>
<FlatList
data={posts}
showsVerticalScrollIndicator={false}
snapToInterval={Dimensions.get('window').height - 24}
snapToAlignment={'start'}
decelerationRate={'fast'}
onViewableItemsChanged={onViewRef.current}
viewabilityConfig={viewConfigRef.current}
renderItem={({item}) => <Post
post={item}
paused={activeVideo !== item.id}
/>}
/>
</View>
)}
Post.js
const Post = (props) => {
const [post, setPost] = useState(props.post);
const [paused, setPaused] = useState(props.paused);
console.log(props.paused)
const onPlayPausePress = () => {
setPaused(!paused);
};
const onPlayPausePress2 = () => {
setPaused(!paused);
};
return (
<View style={styles.container}>
<TouchableWithoutFeedback>
<Image
source={{uri: post.poster}}
style={styles.video2}
/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={onPlayPausePress}>
<Video
source={post.postUrl}
style={styles.video}
onError={(e)=> console.log(e)}
resizeMode={'cover'}
repeat
paused={paused}
/>
</TouchableWithoutFeedback>
</View>
)}
so here's the code:
export default () => {
const [albums, setAlbums] = useState([]);
useEffect(() => {
MediaLibrary.getAlbumsAsync().then((tmpAlbums) => {
setAlbums(tmpAlbums);
});
}, []);
return (
<View>
{albums && (
<FlatList
data={albums}
renderItem={({ item }) => {
<Text>{item.title}</Text>;
}}
/>
)}
</View>
);
};
I'm sure that state updates because I logged it and it was updated, I already have the permissions and I've just removed it for simplicity. I've tried everything and yet, nothing shows on the component/screen.
You are not returning the Text.
Either do
{albums && (
<FlatList
data={albums}
renderItem={({ item }) => {
return (<Text>{item.title}</Text>)
}}
/>
)}
Or
{albums && (
<FlatList
data={albums}
renderItem={({ item }) => (
<Text>{item.title}</Text>)
)}
/>
)}
I'm building a chat app using React Native and Firebase, All code is fine, but I want to show only one user in the list.
How to show only one specific user and not all?
For example:
Peter
John
Michael
Antony
Administrator
I want show Administrator, not all users.
state = {
users:[] }
componentWillMount(){
let dbRef = firebase.database().ref('users');
dbRef.on('child_added', (val) => {
let person = val.val();
person.phone = val.key;
if(person.phone===User.phone){
User.name = person.name
} else {
this.setState((prevState) => {
return {
users: [...prevState.users, person]
}
})
}
}) }
renderRow = ({item}) => {
return (
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Chat', item)}
style={{padding:10, fontSize: 16, color:'#00F0C8', borderBottomColor: '#ccc', borderBottomWidth:1}}>
<Text style={{fontSize:20}}>{item.name}</Text>
</TouchableOpacity>
) }
render(){
return(
<SafeAreaView>
<Text>These are the Users list</Text>
<Card style={styles.maincard}>
<FlatList
data={this.state.users}
renderItem={this.renderRow}
keyExtractor={(item) => item.phone}
/>
</Card>
</SafeAreaView>
)}
Well, you can try to filter the list,
render(){
return(
<SafeAreaView>
<Text>These are the Users list</Text>
<Card style={styles.maincard}>
<FlatList
data={this.state.users.filter(elem => elem.name === "Administrator")}
renderItem={this.renderRow}
keyExtractor={(item) => item.phone}
/>
</Card></SafeAreaView>)}