I am getting a list of data using map not flatlist, I want to use .map not flatlist, when I apply ActivityIndicator to it while fetching the data, it did not work see below
Below is my code
<View>
{dataList.map((dataList, index) =>
<Text key={index} >{dataList.category_name}</Text>
<Text key={index} >{dataList.category_number}</Text>
)}
</View>
When I tried it with ActivityIndicator see below
{ dataList ?
<View>
{dataList.map((dataList, index) =>
<Text key={index} >{dataList.category_name}</Text>
<Text key={index} >{dataList.category_number}</Text>
)}
</View>
:
<ActivityIndicator />
}
It the not work, I will need your help with this.
Thanks in advance
Try using a boolean for your conditional render such as a loading state which you can easily toggle on and off at the beginning of the fetch and at the end respectively. You can also state the logic of your map outside of your component so it looks way cleaner and easy to read like this example:
import React from 'react';
import { Text, View, ActivityIndicator } from 'react-native';
const dataList = [
{ category_name: 'pop', category_number: 1 },
{ category_name: 'dance', category_number: 2 },
{ category_name: 'hiphop', category_number: 3 },
];
const renderDataList = () => {
return dataList.map((dataList, index) => (
<View>
<Text>{dataList.category_name}</Text>
<Text>{dataList.category_number}</Text>
</View>
));
};
const App = () => {
const [isLoading, setIsloading] = React.useState(false);
return <View>{isLoading ? <ActivityIndicator /> : renderDataList()}</View>;
};
export default App;
Your output would be for false:
Your output for true would be:
Related
I have a text input component that uses text input from react native paper, I want to make a place autocomplete by calling google place autocomplete API
right now I can display the suggestion but I can't change the text input value with the value of the suggestion that has been clicked
screenshot of component
since I use Controller from react hook form I thought I could use setValue from useForm to change the value but it didn't do anything when I try to call setValue to change textInput value to one of the suggested value
import React from "react";
import { FlatList, StyleSheet, TouchableOpacity, View } from "react-native";
import { Text, TextInput, Colors } from "react-native-paper";
import { Controller, useForm } from "react-hook-form";
import axiosInstance from "services/axiosInstance";
export default React.forwardRef(
(
{
name,
label,
placeholder,
control,
style: addOnStyle,
...props
},
ref
) => {
const { setValue } = useForm();
const [addressList, setAddressList] = React.useState([])
const getAddressList = async (input) => {
if (input == null || input.match(/^ *$/) !== null) {
setAddressList([])
} else {
const response = await axiosInstance.get(
`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${input}&components=country:us&language=en&key=API_KEY`
)
setAddressList([])
if (response?.data?.status === "OK") {
response?.data?.predictions?.map((item) => setAddressList(addressList => [...addressList, item.description]))
} else {
setAddressList(["Address not found."])
}
}
}
return (
<View style={{ ...styles.viewInput, ...addOnStyle }}>
<Controller
control={control}
name={name}
defaultValue=""
render={({
field: { onChange, onBlur, value, name },
fieldState: { error },
}) => {
return (
<>
<TextInput
label={label}
name={name}
placeholder={placeholder}
onBlur={onBlur}
onChangeText={(val) => onChange(val, getAddressList(val))}
error={!!error?.message}
value={value}
ref={ref}
{...props}
/>
{error?.message ? (
<Text style={styles.textError}>{error?.message}</Text>
) : null}
{addressList.length > 0 ?
<View style={styles.addressListContainer}>
<FlatList
keyExtractor={(_, i) => String(i)}
data={addressList}
renderItem={({ item, index }) => {
return (
<TouchableOpacity
activeOpacity={1}
style={[styles.addressListItem, index==0 ? {borderTopWidth: 0} : {borderTopWidth: 1}]}
onPress={() => {setAddressList([]), setValue(name, item)}}
>
<Text numberOfLines={1}>{item}</Text>
</TouchableOpacity>
)
}}
/>
</View>
: null}
</>
);
}}
/>
</View>
);
}
);
UPDATE Changed the title to match the current question
I think for now my problem is since the control is set from the outside of the component that makes it can't be changed with setValue from inside the component, now I wonder if we could use multiple control on one Controller?
I solve it by changing setValue(name, item) on onPress to onChange(item) it doesn't need another control
I have a component called Header that look like this:
import React from 'react'
import {StyleSheet, TouchableOpacity, View, StyleProp, ViewStyle} from 'react-native'
import {Text} from '..'
import Icon from 'react-native-vector-icons/MaterialIcons'
import {theme} from '#app/presentations/utils/styles'
import {useNavigation} from '#react-navigation/core'
interface IHeaderProps {
title: string
headerRight?: () => JSX.Element | false | undefined
onGoBack?: () => void
hideBackButton?: boolean
style?: StyleProp<ViewStyle>
}
const Header: React.FC<IHeaderProps> = props => {
const navigation = useNavigation()
const goBack = () => {
props.onGoBack ? props.onGoBack : navigation.goBack()
}
return (
<View style={[styles.container, props.style]}>
<View style={styles.leftContent}>
{props?.hideBackButton ? null : (
<TouchableOpacity onPress={goBack} testID="headerBackButton">
<Icon name={'chevron-left'} size={22} color={theme.colors.black} />
</TouchableOpacity>
)}
</View>
<View style={{flex: 1, flexGrow: 10, alignItems: 'center'}}>
<Text maxLines={2} style={{paddingHorizontal: 8, textAlign: 'center'}} type="semibold">
{props.title}
</Text>
</View>
<View style={styles.rightContent}>{props.headerRight && props.headerRight()}</View>
</View>
)
}
export default Header
Focus on TouchableOpacity, I want to fire the onPress of it using testId, but looks like it won't fire.
it('Should have correct behavior', () => {
const goBackFn = jest.fn()
const props: IHeaderProps = {
title: 'My Header',
onGoBack: goBackFn,
}
const {component, getByTestId, queryAllByText} = renderComponent(props)
expect(component).toMatchSnapshot()
expect(queryAllByText('My Header').length).toBe(1)
expect(getByTestId('headerBackButton')).toBeTruthy()
fireEvent.press(getByTestId('headerBackButton'))
expect(goBackFn).toBeCalled()
})
The error message was like this
means that my goBack function never executed. I wondering why.
Then I check the snapshots of my Header component, it is not show TouchableOpacity but it shows View with onClick function on it
<View
accessible={true}
collapsable={false}
focusable={true}
nativeID="animatedComponent"
onClick={[Function]}
onResponderGrant={[Function]}
onResponderMove={[Function]}
onResponderRelease={[Function]}
onResponderTerminate={[Function]}
onResponderTerminationRequest={[Function]}
onStartShouldSetResponder={[Function]}
style={
Object {
"opacity": 1,
}
}
testID="headerBackButton"
>
My question is how do I execute onPress on TouchableOpacity ?
I fixed this. At least there is two problem from my implementation.
On the Header component, I forgot to add parenthesis () on props.onGoBack function. It should be props.onGoBack() not props.onGoBack
I need to add await waitFor(() => { ...wait for my getTestById to be truthy })
I have a flat list with some hardcoded data. How can I implement the Activity indicator to spin and to be displayed until the flat list data is completely displayed on the screen? Below is my code. Thanks
import React, {useState} from 'react';
import { View, FlatList, TouchableOpacity, ActivityIndicator } from 'react-native';
import { MainScreenCard } from '../mainScreen.components/mainScreen.card';
import { Spacer } from '../assets.driveAround/spacer';
export const MainScreen = ({navigation}) => {
return(
<>
<FlatList
data={[
{ name: 1 },
{ name: 2 },
{ name: 3 },
{ name: 4 }
]}
renderItem={() => (
<TouchableOpacity onPress={() => navigation.navigate("Login")}>
<Spacer position="bottom" size="large">
<MainScreenCard/>
</Spacer>
</TouchableOpacity>
)}
keyExtractor={(item) => item.name}
contentContainerStyle={{ padding: 16 }}
/>
</>
);
}
There are two main options depending on how you want to refresh. If you want to pull from the top of the screen to refresh provide it a refresh control
https://reactnative.dev/docs/refreshcontrol
<ScrollView
contentContainerStyle={styles.scrollView}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
/>
}
>
<Text>Pull down to see RefreshControl indicator</Text>
</ScrollView>
Otherwise, another simple option is to use an ActivityIndicator to show a spinner overtop of the view
https://reactnative.dev/docs/activityindicator
const [loading, setLoading] = useState(false)
...
<ActivityIndicator size="large" color="#00ff00" animating={loading}/>
I have seen is a common error and I tried different solutions with no result.
This is my code so far, rarely is working and the fetch is returning a proper movies array but most of the times is sending back an error:
import React, { useState, useEffect } from "react";
import { Text, View, Image, ScrollView, ActivityIndicator } from "react-native";
function Dashboard() {
const [loading, setLoading] = useState(true);
const [popularMovies, setPopularMovies] = useState([])
const popularMoviesUrl =
".....";
const fetchMovies = () => {
fetch(popularMoviesUrl)
.then(res => res.json())
.then(setPopularMovies)
.then(console.log(popularMovies));
};
useEffect(() => {
fetchMovies();
}, []);
const { results } = popularMovies;
return loading ? (
<View style={styles.loader}>
<ActivityIndicator size="large" color="#dcae1d" animating />
</View>
) : (
<ScrollView horizontal style={styles.container}>
{results.map(movie => (
<View key={movie.id}>
<Text style={styles.container}>{movie.title}</Text>
<Image
style={styles.poster}
source={{
uri: `https://image.tmdb.org/t/p/w500${movie.poster_path}`
}}
/>
</View>
))}
<Text>thfh</Text>
</ScrollView>
);
}
export default Dashboard;
Seems to be an issue referencing the popular movies returned from your fetch. Set your popularMovies state as the results property from your fetch rather than the for JSON.
So change:
.then(setPopularMovies)
to...
.then(resJson => setPopularMovies(resJson.results))
Then remove the results variable and reference popularMovies directly.
I've 4 FlatLists with maxHeight set to 200 inside a ScrollView.
<ScrollView>
<FlatList/>
<FlatList/>
<FlatList/>
<FlatList/>
</ScrollView>
and when I try to scroll a FlatList, it doesn't scroll but the ScrollView scrolls. How do I fix this issue ?
Full Source Code
import { Component, default as React } from 'react';
import { FlatList, ScrollView, Text } from 'react-native';
export class LabScreen extends Component<{}> {
render() {
return (
<ScrollView>
{this.renderFlatList('red')}
{this.renderFlatList('green')}
{this.renderFlatList('purple')}
{this.renderFlatList('pink')}
</ScrollView>
);
}
getRandomData = () => {
return new Array(100).fill('').map((item, index) => {
return { title: 'Title ' + (index + 1) };
});
};
renderFlatList(color: string) {
return (
<FlatList
data={this.getRandomData()}
backgroundColor={color}
maxHeight={200}
marginBottom={50}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
);
}
}
snack.expo link
We can use the built-in nestedscrollenabled prop for the children FlatList/ScrollView components.
<FlatList nestedScrollEnabled />
This is only required for Android (Nested scrolling is supported by default on iOS).
I was having a very similar issue until I came across an almost complete solution in a very helpful comment on one of the GitHub issues for the react-native project: https://github.com/facebook/react-native/issues/1966#issuecomment-285130701.
The issue is that the parent component is the only one registering the scroll event. The solution is to contextually decide which component should actually be handling that event based on the location of the press.
You'll need to slightly modify your structure to:
<View>
<ScrollView>
<View>
<FlatList />
</View>
<View>
<FlatList />
</View>
<View>
<FlatList />
</View>
<View>
<FlatList />
</View>
</ScrollView>
</View>;
The only thing I had to change from the GitHub comment was to use this._myScroll.contentOffset instead of this.refs.myList.scrollProperties.offset.
I've modified your fully working example in a way that allows scrolling of the inner FlatLists.
import { Component, default as React } from "react";
import { View, FlatList, ScrollView, Text } from "react-native";
export default class LabScreen extends Component<{}> {
constructor(props) {
super(props);
this.state = { enableScrollViewScroll: true };
}
render() {
return (
<View
onStartShouldSetResponderCapture={() => {
this.setState({ enableScrollViewScroll: true });
}}
>
<ScrollView
scrollEnabled={this.state.enableScrollViewScroll}
ref={(myScroll) => (this._myScroll = myScroll)}
>
{this.renderFlatList("red")}
{this.renderFlatList("green")}
{this.renderFlatList("purple")}
{this.renderFlatList("pink")}
</ScrollView>
</View>
);
}
getRandomData = () => {
return new Array(100).fill("").map((item, index) => {
return { title: "Title " + (index + 1) };
});
};
renderFlatList(color: string) {
return (
<View
onStartShouldSetResponderCapture={() => {
this.setState({ enableScrollViewScroll: false });
if (
this._myScroll.contentOffset === 0 &&
this.state.enableScrollViewScroll === false
) {
this.setState({ enableScrollViewScroll: true });
}
}}
>
<FlatList
data={this.getRandomData()}
backgroundColor={color}
maxHeight={200}
marginBottom={50}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
</View>
);
}
}
Hopefully you find this useful!
This is the simplest answer that requires zero configuration.. and it works like a charm
<ScrollView horizontal={false}>
<ScrollView horizontal={true}>
<Flatlist
....
....
/>
</ScrollView>
</ScrollView>
I fixed my problem with nested FlatList not being able to scroll items on android by simply importing FlatList
import { FlatList } from 'react-native-gesture-handler';
If this would not work, also try to import ScrollView.
import { ScrollView } from 'react-native';
// OR
import { ScrollView } from 'react-native-gesture-handler';
You need to play around with these imports, at least it worked in my case.
Try to set the FlatList as nested
nestedScrollEnabled={true}
Using View with a flex:1 instead of ScrollView worked for me.
Use map instead of Flatlist, same result and don't break the application
Minha conta
{
buttonsProfile.map(button => (
<ArrowButton
key={button.key}
title={button.title}
iconName={button.icon}
toogle={button.toogle}
onPress={() => {navigation.navigate(button.route)}}
/>
))
}
The better answer is to put a horizontal ScrollView inside of the other ScrollView and then the FlatList