react native: Displays a single table with the data - javascript

In my code I expect to get only one table with the data but what happens is that I get a lot of tables with the same data and it is not clear to me why.
Lots of tables are accepted and I should get only one table.
I would be happy to help with this
export const ActionModal = (props: any) => {
const { pointsData } = useGetPoints();
const [tableHead] = useState(['אזור', 'אתר', 'נ`ק איסוף', 'מיקום']);
const [tableData, setTableData] = useState([]);
const arrangeData = () => {
let rows: any[] = [];
pointsData.forEach(e => {
let row = [e.area, e.site, e.gatheringPoint, e.location];
rows.push(row);
});
setTableData(rows);
}
useEffect(() => {
arrangeData();
}, []);
const renderItem = ({ item }: any) => (
<View style={styles.item}>
<View style={styles.tableView}>
<Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff' }}>
<Row data={tableHead} style={styles.head} textStyle={styles.text} />
<Rows data={tableData} textStyle={styles.text} />
</Table>
</View>
<Text style={{ fontSize: 18 }}>{item.area}, {item.site}, {item.gatheringPoint}, {item.location}</Text>
</View>
)
return (
<Modal
animationType={'slide'}
transparent={false}
visible={props.actionModalVisible}
onRequestClose={() => {
console.log('Modal has been closed.');
}}>
<View style={styles.modal}>
{pointsData.length ?
<FlatList
data={pointsData}
renderItem={renderItem}
keyExtractor={item => item.gatheringID}
/> :
<ActivityIndicator size="large" />}
</View>
<Button
title="סגור"
onPress={props.onClose}
/>
</Modal>
);
};

Table are rendered inside a item of flatlist
the function renderItem will repeate like a number of row of you array , this why you get lot of table ..
to fix this you need to pull out of flatlist like this to rendering table once time :
export const ActionModal = (props: any) => {
const { pointsData } = useGetPoints();
const [tableHead] = useState(['אזור', 'אתר', 'נ`ק איסוף', 'מיקום']);
const [tableData, setTableData] = useState([]);
const arrangeData = () => {
let rows: any[] = [];
pointsData.forEach(e => {
let row = [e.area, e.site, e.gatheringPoint, e.location];
rows.push(row);
});
setTableData(rows);
}
useEffect(() => {
arrangeData();
}, []);
const renderItem = ({ item }: any) => (
<Text style={{ fontSize: 18 }}>{item.area}, {item.site}, {item.gatheringPoint}, {item.location}</Text>
)
return (
<Modal
animationType={'slide'}
transparent={false}
visible={props.actionModalVisible}
onRequestClose={() => {
console.log('Modal has been closed.');
}}>
<View style={styles.modal}>
{pointsData.length ?
<View style={styles.item}>
<View style={styles.tableView}>
<Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff' }}>
<Row data={tableHead} style={styles.head} textStyle={styles.text} />
<Rows data={tableData} textStyle={styles.text} />
</Table>
</View>
<FlatList
data={pointsData}
renderItem={renderItem}
keyExtractor={item => item.gatheringID}
/>
</View>:
<ActivityIndicator size="large" />}
</View>
<Button
title="סגור"
onPress={props.onClose}
/>
</Modal>
);
};

Related

How to display fetch data inside the table

How to get fetch data inside the react-native table here ?
When i tried to fetch data, the table display empty with this codes, so where and what to do for get the data from API and display in the table in react native.
getData() {
fetch('https://www.lampmonitor.com/lampmonitor/api/auth/web/lampControls?projectId=595&pageSize=50')
.then(responce => responce.json())
.then(data => {
this.setState({
tableData: data
});
});
}
render() {
const state = this.state;
const { tableData } = state;
return (
<View style={styles.container}>
<ScrollView horizontal={true}>
<View>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
<Row
data={state.tableHead}
widthArr={state.widthArr}
style={styles.header}
textStyle={styles.text}
/>
</Table>
<ScrollView style={styles.dataWrapper}>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
{tableData.map((rowData, index) => (
<Rows
key={index}
data={rowData}
widthArr={state.widthArr}
style={[
styles.row,
index % 2 && {backgroundColor: '#F7F6E7'},
]}
textStyle={styles.text}
/>
))}
</Table>
</ScrollView>
</View>
</ScrollView>
</View>
);
}
This is an example of how to do it using React hooks.
https://reactjs.org/docs/hooks-state.html
You have many errors and I think you need to brush up on the differences between Class components and Functional components using React Hooks.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default TableComponent;
import React, { useState, useEffect } from 'react';
const TableComponent = () => {
const [tableData, setTableData] = useState({});
useEffect(() => {
async function getData() {
fetch('https://www.lampmonitor.com/lampmonitor/api/auth/web/lampControls?projectId=595&pageSize=50')
.then(responce => responce.json())
.then(data => {
setTableData({data});
});
}
getData();
}, []);
return (
<View style={styles.container}>
<ScrollView horizontal={true}>
<View>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
<Row
data={tableData.tableHead}
widthArr={tableData.widthArr}
style={styles.header}
textStyle={styles.text}
/>
</Table>
<ScrollView style={styles.dataWrapper}>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
{tableData.map((rowData, index) => (
<Rows
key={index}
data={rowData}
widthArr={tableData.widthArr}
style={[
styles.row,
index % 2 && {backgroundColor: '#F7F6E7'},
]}
textStyle={styles.text}
/>
))}
</Table>
</ScrollView>
</View>
</ScrollView>
</View>
);
}

How to output only 5 elements in a FlatList from JSON? React-native

I have a JSON file where new news items are constantly stored and added, their number is constantly changing. I want to output only the last 3 elements from this JSON file to the FlatList. How to do it?
Here is my JSON receipt and my FlatList:
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const getNewsMain = async () => {
try {
const response = await fetch(`https://cdn.ertil-gorod.ru/json/ertnews.json?nocache`);
const json = await response.json();
setData(json.ertnews);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
useEffect(() => {
getNewsMain();
}, []);
<FlatList
data={data}
initialNumToRender={5}
keyExtractor={({ id }, index) => id}
renderItem={ ( { item } ) => (
<TouchableOpacity
style={ styles.ert__news__item }
onPress={ ( ) => navigation.navigate( 'FullNews', item ) }>
<Image
style={ styles.ert__image__news }
source={ { uri: item.img } }
/>
<Text style={ styles.ert__title__news }>{ item.name }</Text>
<Text style={ styles.ert__anons__news }>{ item.anons }</Text>
</TouchableOpacity>
)} />
If data is an array you can use the Array.slice
<FlatList
data={data.slice(-3)}
initialNumToRender={5}
keyExtractor={({ id }, index) => id}
renderItem={ ( { item } ) => (
<TouchableOpacity
style={ styles.ert__news__item }
onPress={ ( ) => navigation.navigate( 'FullNews', item ) }>
<Image
style={ styles.ert__image__news }
source={ { uri: item.img } }
/>
<Text style={ styles.ert__title__news }>{ item.name }</Text>
<Text style={ styles.ert__anons__news }>{ item.anons }</Text>
</TouchableOpacity>
)}
/>

How do I get the document ID of a specific document in Firebase on React Native?

I'm working on a project that allows users to write anonymous letters addressed to people by name and I want to add a like/dislike functionality to the app. I was confused on how to get the specific document ID for that post and also incrementing the likeCount by 1 (in the areas where the "????" are at in the code below) ? I want it to update the field "likeCount" in firebase by 1 when the thumbs up icon is pressed.
This is the portion of my code that contains the posts (data from firebase) that is mapped for each firebase document:
function Home() {
const [posts, setPosts] = useState([]);
const [searchValue, setSearchValue] = useState("");
const [filteredPosts, setFilteredPosts] = useState([]);
const collectionRef = collection(db, "posts");
useEffect(() => {
const getPosts = async () => {
const data = await getDocs(collectionRef);
const filteredRef = query(
collectionRef,
where(`recipiant`, "==", `${searchValue}`)
);
const querySnapshot = await getDocs(filteredRef);
let posts = [];
querySnapshot.forEach((doc) => {
posts.push(doc.data());
});
setFilteredPosts(posts);
setPosts(
searchValue
? filteredPosts
: data.docs.map((doc) => ({ ...doc.data() }))
);
};
getPosts();
}, [searchValue, filteredPosts]);
return (
<ImageBackground source={image} style={styles.image}>
<SafeAreaView style={styles.container}>
<ScrollView>
<View style={styles.header}>
<Text style={styles.title}>Home</Text>
</View>
<Pressable>
<Input
placeholder="Search for a name"
inputContainerStyle={styles.searchbar}
inputStyle={styles.searchInput}
placeholderTextColor="gray"
onChangeText={(text) => setSearchValue(text)}
/>
</Pressable>
{posts.map((post, key) => {
return (
<View style={styles.postWrapper} key={key}>
<View style={styles.btnWrapper}>
<View style={styles.likeBtn}>
<Icon
name="thumbs-up"
size={25}
color="#fff"
onPress={() => {
const postRef = doc(db, "posts", `????`);
updateDoc(postRef, {
likeCount: ????,
});
}}
/>
<Text style={styles.likeCount}>{post.likeCount}</Text>
</View>
<Icon
name="thumbs-down"
size={25}
color="#fff"
onPress={() => {}}
/>
</View>
<Card
containerStyle={{
backgroundColor: "rgba( 255, 255, 255, 0.5 )",
borderRadius: 50,
height: 300,
marginBottom: 25,
width: 330,
backdropFilter: "blur( 20px )",
padding: 20,
}}
>
<Card.Title style={styles.notepadHeader}>Message.</Card.Title>
<View style={styles.center}>
<ScrollView>
<Text style={styles.notepadText}>
To: <Text style={styles.name}>{post.recipiant}</Text>
</Text>
<Text style={styles.notepadTextLetter}>
{post.letter}
</Text>
<Text style={styles.notepadFooter}>
From:{" "}
<Text
style={{
color: "#9e4aba",
fontSize: 20,
}}
>
{post.displayName}
</Text>
</Text>
</ScrollView>
</View>
</Card>
</View>
);
})}
</ScrollView>
</SafeAreaView>
</ImageBackground>
);
}
This is how my Firestore looks like and I want to retrieve the document id in the circle.
First, you can add the document ID in 'posts' array as shown below:
const posts = querySnapshot.docs.map((d) => ({ id: d.id, ...d.data() }));
setFilteredPosts(posts);
Then you can read post ID when required:
<Icon
name = "thumbs-up"
size = {25}
color = "#fff"
onPress = {() => {
const postRef = doc(db, "posts", post.id);
updateDoc(postRef, {
likeCount: ?? ?? ,
});
}
}
/>
This will give you the particular doc and perform updateDoc query accordingly.
query(collections('collection_name), where(documentId(), '==', 'your_post_id'))

ReactNative rerenders component when the user opens the page

I have two components the first where user can add a place to the favorites and the second is favorites component where user may see all his favorite places. When the user for the first time opens the favorites component everything works as expected: all the favorite places that user has already added to the favorites rendered. But if user go to the first component and add one more place and then go to the second component new place will not appear because component has already rendered and the state didn't changed because useEffect not triggered. Help me please what should I use in my FavouritePlaces component instead of useEffect to rerender this component every time when user open FavouritePlaces?
Component where user can add to favorites:
const ModalWindow = ({navigateToPlace, sendDataToParent, visible, marker}: HomeNavigationProps<"ModalWindow">) => {
const regex = /(<([^>]+)>)|( )|(&nbps)/ig;
const result = marker.description.replace(regex, '');
const [favKeys, setFavKeys] = useState([]);
const onDismiss = () => {
sendDataToParent(false)
}
const onNavigationTap = () => {
onDismiss();
navigateToPlace(true, marker.coordinates);
}
const getFavourites = async () => {
let keys = []
keys = await AsyncStorage.getAllKeys()
setFavKeys(keys);
}
const onHeartPress = async () => {
const jsonValue = JSON.stringify(marker)
try {
if (favKeys.includes(marker.id.toString())){
await AsyncStorage.removeItem(marker.id.toString())
await getFavourites();
} else {
await AsyncStorage.setItem(marker.id.toString(), jsonValue)
await getFavourites();
}
} catch (e) {
console.log('error in onHeartPress', e)
}
console.log('Done.')
//remove after test
try {
await AsyncStorage.removeItem('__react_native_storage_test')
} catch(e) {
// remove error
}
console.log('Done.')
}
return (
<Modal visible={visible} onDismiss={onDismiss} contentContainerStyle={styles.container}>
<IconButton
style={
styles.iconButton
}
icon="close"
color={Colors.black}
size={30}
onPress={() => onDismiss()}
/>
<Text
style={{fontStyle: "italic", fontSize: 20, alignSelf: "center", maxWidth: '75%'}}>{marker.title}
</Text>
<CustomCarousel {...{marker}} />
<ScrollView showsVerticalScrollIndicator={false} style={{marginTop: '3%', marginLeft: '3%', marginRight: '3%'}}>
<Text>{result}</Text>
</ScrollView>
<View style={{flexDirection: "row", justifyContent: "space-around", marginLeft: "3%", marginRight: "3%", marginBottom: "15%"}}>
<TouchableOpacity onPress={() => onNavigationTap()}>
<View style={{flexDirection: "row", alignItems: "center"}}>
<Ionicons size={height/20} name={'navigate-circle-outline'} />
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => onHeartPress()}>
{marker.id ?
<View style={{flexDirection: "row", alignItems: "center"}}>
{favKeys.includes(marker.id.toString()) ? <Ionicons size={height/20} name={'heart-dislike'} /> : <Ionicons size={height/20} name={'heart'} />}
</View> : undefined}
</TouchableOpacity>
</View>
</Modal>
);
}
export default ModalWindow;
My Favorite Places component:
const FavouritePlaces = ({navigation}: HomeNavigationProps<"FavouritePlaces">) => {
const [markers, setMarkers] = useState([]);
useEffect(() => {
const getFavourites = async () => {
let keys = []
try {
keys = await AsyncStorage.getAllKeys()
} catch (e) {
// read key error
}
let values
try {
let forDeletion = ['__react_native_storage_test', 'NAVIGATION_STATE_KEY-40.0.0'];
keys = keys.filter(item => !forDeletion.includes(item))
values = await AsyncStorage.multiGet(keys)
setMarkers(values)
} catch (e) {
// read error
}
}
getFavourites();
}, [])
const transition = (
<Transition.Together>
<Transition.Out type='fade'/>
<Transition.In type='fade'/>
</Transition.Together>
);
const list = useRef<TransitioningView>(null);
const theme = useTheme()
const width = (wWidth - theme.spacing.m * 3) / 2;
const [footerHeight, setFooterHeight] = useState(0);
return (
<Box flex={1} backgroundColor="background">
<StatusBar style="black" />
<Header
title="Избранные места"
left={{icon: 'menu', onPress: () => navigation.openDrawer()}}
right={{icon: 'shopping-bag', onPress: () => true}}
/>
<Box flex={1}>
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{
paddingBottom: footerHeight,
}}>
<Transitioning.View ref={list} transition={transition} style={{}}>
{markers ?
<Box flexDirection='row' style={{justifyContent: "space-around"}}>
<Box>
{markers
.filter((_, i) => i % 2 === 0).map((currentMarker) => <Picture
key={currentMarker}
place={currentMarker}
width={width}
height={height}
/>)}
</Box>
<Box>
{markers
.filter((_, i) => i % 2 !== 0).map((currentMarker) => <Picture
key={currentMarker}
place={currentMarker}
width={width}
height={height}/>)}
</Box>
</Box> : undefined}
</Transitioning.View>
</ScrollView>
{/*<TopCurve footerHeight={footerHeight}/>*/}
<Box position='absolute' bottom={0} left={0} right={0} onLayout={({
nativeEvent: {
layout: {height},
}
}) => setFooterHeight(height)}>
</Box>
</Box>
</Box>
)
}
export default FavouritePlaces
Try this
useEffect(() => {
// ... Your code goes here
}, [navigation]);
this will render whenever update in navigate
I've found the solution. React navigation has hook useIsFocused, so what can we do is:
import { useIsFocused } from "#react-navigation/native";
const isFocused = useIsFocused();
useEffect(() => {
// ... Your code goes here
}, [isFocused]);
You can use React Context API to share the state across the screens.
Check out this Expo Snack I created.
import {
CompositeNavigationProp,
NavigationContainer,
NavigatorScreenParams,
} from '#react-navigation/native';
import {
createStackNavigator,
StackNavigationProp,
} from '#react-navigation/stack';
import * as React from 'react';
import {
Button,
FlatList,
ListRenderItem,
Text,
TextInput,
View,
} from 'react-native';
type MainStackParamsList = {
FavoritePlacesScreen: undefined;
};
type ModalStackParamsList = {
MainStack: NavigatorScreenParams<MainStackParamsList>;
AddFavoritePlacesModal: undefined;
};
type FavoritePlace = {
id: number;
name: string;
};
type FavoritePlacesContextValue = {
favoritePlaces: FavoritePlace[];
addNewFavoritePlace: (favoritePlace: FavoritePlace) => void;
removeFavoritePlace: (id: number) => void;
};
const FavoritePlacesContext = React.createContext<FavoritePlacesContextValue>({
favoritePlaces: [],
addNewFavoritePlace: () => {},
removeFavoritePlace: () => {},
});
const MainStack = createStackNavigator<MainStackParamsList>();
type FavoritePlacesScreenProps = {
navigation: CompositeNavigationProp<
StackNavigationProp<MainStackParamsList, 'FavoritePlacesScreen'>,
StackNavigationProp<ModalStackParamsList>
>;
};
const FavoritePlacesScreen = ({navigation}: FavoritePlacesScreenProps) => {
const {favoritePlaces, removeFavoritePlace} = React.useContext(
FavoritePlacesContext,
);
const renderItem = React.useCallback<ListRenderItem<FavoritePlace>>(
({item}) => {
return (
<View style={{height: 50, padding: 10, flexDirection: 'row'}}>
<Text style={{fontSize: 16}}>{item.name}</Text>
<Button onPress={() => removeFavoritePlace(item.id)} title="Remove" />
</View>
);
},
[removeFavoritePlace],
);
return (
<View style={{flex: 1}}>
<FlatList
data={favoritePlaces}
keyExtractor={(item) => String(item.id)}
renderItem={renderItem}
/>
<Button
onPress={() => {
navigation.navigate('AddFavoritePlacesModal');
}}
title="Add new favorite"
/>
</View>
);
};
const MainStackNavigator = () => {
return (
<MainStack.Navigator>
<MainStack.Screen
component={FavoritePlacesScreen}
name="FavoritePlacesScreen"
/>
</MainStack.Navigator>
);
};
type AddFavoritePlacesModalProps = {
navigation: StackNavigationProp<
ModalStackParamsList,
'AddFavoritePlacesModal'
>;
};
const AddFavoritePlacesModal = ({navigation}: AddFavoritePlacesModalProps) => {
const {addNewFavoritePlace} = React.useContext(FavoritePlacesContext);
const [favoritePlaceName, setFavoritePlaceName] = React.useState('');
const handleOnSave = React.useCallback(() => {
addNewFavoritePlace({
id: Date.now(),
name: favoritePlaceName,
});
navigation.goBack();
}, [addNewFavoritePlace, favoritePlaceName, navigation]);
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<View style={{borderRadius: 6, borderWidth: 1, borderColor: '#333'}}>
<TextInput
onChangeText={setFavoritePlaceName}
placeholder="Name your favorite place"
/>
</View>
<Button onPress={handleOnSave} title="Save" />
</View>
);
};
// Put the favorite places list screen and the add favorite place modal here.
// Then use FavoritePlacesContext.Provider to wrap ModalStack.Navigator in order
// for the context to be available on MainStack
const ModalStack = createStackNavigator<ModalStackParamsList>();
const ModalNavigator = () => {
const [favoritePlaces, setFavoritePlaces] = React.useState<FavoritePlace[]>(
[],
);
const addNewFavoritePlace = React.useCallback(
(favoritePlace: FavoritePlace) => {
setFavoritePlaces((prev) => [...prev, favoritePlace]);
},
[],
);
const removeFavoritePlace = React.useCallback((id: number) => {
setFavoritePlaces((prev) =>
prev.filter((favoritePlace) => favoritePlace.id !== id),
);
}, []);
return (
<FavoritePlacesContext.Provider
value={{
favoritePlaces,
addNewFavoritePlace,
removeFavoritePlace,
}}
>
<ModalStack.Navigator headerMode="none">
<ModalStack.Screen component={MainStackNavigator} name="MainStack" />
<ModalStack.Screen
component={AddFavoritePlacesModal}
name="AddFavoritePlacesModal"
options={{headerShown: false}}
/>
</ModalStack.Navigator>
</FavoritePlacesContext.Provider>
);
};
const App = () => {
return (
<NavigationContainer>
<ModalNavigator />
</NavigationContainer>
);
};
export default App;

How to pass props to FlatList with renderScene in react-native-tab-view?

I'm a newbie in React Native and trying to pass props to ListHeaderComponent in FlatList
Here's the code:
const FirstRoute = (props) => {
const _renderHeader = () => {
return(
<View>
{props.isFollowed &&
<TouchableOpacity onPress={props.onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
</View>
)
}
return(
<View style={[styles.scene, { backgroundColor: '#ff4081' }]}>
<FlatList
data={data}
keyExtractor={item => item.id}
renderItem={itemData => ( <Image source={itemData.item.id} style={{height: WIDTH/3, width: WIDTH/3}} />)}
ListHeaderComponent={_renderHeader}
/>
</View>
)
};
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const initialLayout = { width: Dimensions.get('window').width };
export default function Parent() {
const [index, setIndex] = React.useState(0);
const [routes] = useState([
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]);
const [_isFollowed, setIsFollowed] = useState(false);
const _onSubmit = () => {
...
setIsfollowed(true)
}
const renderScene = ({route}) => {
switch(route.key){
case 'first': return <FirstRoute {...props} onSubmit={_onSubmit} isFollowed={_isFollowed} />
case 'second': return <SecondRoute {...props} />
}
};
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
);
}
But when I save it, the screen logs the error: Can't find the value of isFollowed
I think the problem is at the way I pass the props. I'm still learning it. Since when I delete the ListHeaderComponent, the FlatList still generates the list of images well. And I don't know if it has something to do with renderScene
I really don't understand why
Please help me. Thank you very much
Let me get this straight. You need to render _renderHeader dinamically based on _isFollowed state. So, you passed to the first route as props your _onSubmit function and _isFollowed state in order to get to access them at _renderHeader. Right?
As I see you actually doesn't need to do it once your _renderHeader has direct access to both _isFollowed state and _onSubmit function. Try it out as bellow:
export default function Parent() {
const [index, setIndex] = React.useState(0);
const [routes] = useState([
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]);
const [_isFollowed, setIsFollowed] = useState(false);
const initialLayout = { width: Dimensions.get('window').width };
function _onSubmit() {
setIsFollowed(true);
}
function _renderHeader() {
return (
<View>
{_isFollowed &&
<TouchableOpacity onPress={_onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
</View>
);
}
const FirstRoute = () => {
return(
<View style={[styles.scene, { backgroundColor: '#ff4081' }]}>
<FlatList
data={data}
keyExtractor={item => item.id}
renderItem={itemData => ( <Image source={itemData.item.id} style={{height: WIDTH/3, width: WIDTH/3}} />)}
ListHeaderComponent={_renderHeader}
/>
</View>
)
};
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const renderScene = ({route}) => {
switch(route.key){
case 'first': return <FirstRoute />
case 'second': return <SecondRoute />
}
};
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
);
}
Other point I don't understand in your code and couldn't check cause I didn't try to run it was the function bellow:
function _renderHeader() {
return (
<View>
{_isFollowed &&
<TouchableOpacity onPress={_onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
</View>
);
}
If you want to render TouchableOpacity just in case _isFollowed is true you should do it using ternary operator like so:
function _renderHeader() {
return (
<View>
{_isFollowed ?
<TouchableOpacity onPress={_onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
: <></>
}
</View>
);
}

Categories

Resources