react native collapsible tab view labelstyle not working - react-native

I am trying to style the tab names but not working. the prop labelStyle are not exists as Prop but in the documentation its exists.
import React, { memo, useMemo, useCallback, useState, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Dimensions, ScrollView } from 'react-native';
import { RecyclerListView, LayoutProvider, DataProvider } from 'recyclerlistview';
import Header from './Header';
import PropTypes from 'prop-types';
import faker from 'faker';
import { datas } from '../../utils';
import { Tabs } from 'react-native-collapsible-tab-view';
const HEIGHT = 250;
const Main = () => {
const Header = useCallback(() => (
<View style={{flex: 1}}>
<Header/>
</View>
), []);
const renderItem = useCallback(({ item }) => {
return (
<Text>Hello</Text>
)
}, [datas]);
const [currentIndex, setCurrentIndex] = useState(0);
const RenderTabBar = props => {
console.log(JSON.stringify(props));
console.log(JSON.stringify(props.tabNames));
return props.tabNames.map(el => {
return <Text key={Math.random(100).toString()}>{el}</Text>
})
};
return (
<Tabs.Container
containerStyle={{flex: 1, paddingBottom: 60}}
renderHeader={Header}
initialTabName={0}
renderTabBar={RenderTabBar}
headerHeight={HEIGHT}>
<Tabs.Tab style={{flex: 1}} label="s" name="Produkte">
<Tabs.FlatList
data={datas}
renderItem={renderItem}
keyExtractor={item => Math.random(100).toString()}
/>
</Tabs.Tab>
<Tabs.Tab name="Kollektionen">
<Tabs.ScrollView>
<View style={[styles.box, styles.boxA]} />
<View style={[styles.box, styles.boxB]} />
<View style={[styles.box, styles.boxA]} />
<View style={[styles.box, styles.boxB]} />
</Tabs.ScrollView>
</Tabs.Tab>
<Tabs.Tab name="Neuerscheinigungen">
<Tabs.ScrollView>
<View style={[styles.box, styles.boxA]} />
<View style={[styles.box, styles.boxB]} />
<View style={[styles.box, styles.boxA]} />
</Tabs.ScrollView>
</Tabs.Tab>
</Tabs.Container>
)
};
...............................................................................................................................,.........................................................................................

You need to Import the MaterialTabBar to use it in the renderTabBar.
import { Tabs, MaterialTabBar } from 'react-native-collapsible-tab-view'
const tabBar = props => (
<MaterialTabBar
{...props}
indicatorStyle={{ backgroundColor: 'white' }}
style={{ backgroundColor: 'pink' }}
/>
);
const Main = () => {
return (
<Tabs.Container
renderTabBar={tabBar}
>
<Tabs.Tab>
<Text>content</Text>
</Tabs.Tab>
</Tabs.Container>
)
}

Basic usage looks like this:
<
Tabs.Container
...
TabBarComponent = {
(props) => ( <
MaterialTabBar {
...props
}
activeColor = "red"
inactiveColor = "yellow"
inactiveOpacity = {
1
}
labelStyle = {
{
fontSize: 14
}
}
/>
)
} >
{
...
}
<
/Tabs.Container>
https://github.com/PedroBern/react-native-collapsible-tab-view/blob/main/src/MaterialTabBar/TabBar.tsx

Related

Material Top Tab Navigator's body is not loading/ unanle to see

I'm building a react-native screen in which I am having a Material Top Navigator. I don't know why the tab navigator is visible but the component inside it is not showing. I have imported the required dependencies. The component is rendering normally if used without tab navigator.
Main screen code:
import React,{useState,useEffect} from 'react';
import {View, Text,StyleSheet,Image,ScrollView,FlatList } from 'react-native';
import axios from 'axios';
import {Colors} from '../Components/Common/Colors';
import TeamvsTeam from '../Components/TeamvsTeam';
import Heading from '../Components/Common/Heading';
import EventItem from '../Components/EventItem';
import TeamLineup from '../Components/TeamLineup';
import { createMaterialTopTabNavigator } from '#react-navigation/material-top-tabs';
const FixtureDetails = ({route,navigation}) => {
const [fixturedetail,setfixture] = useState();
const {id} = route.params;
useEffect(()=>{
getfixturedetails(id);
},[]);
const getfixturedetails = (id) => {
console.log('Fixture Id -> '+id)
const options = {
method: 'GET',
url: 'https://api-football-v1.p.rapidapi.com/v3/fixtures',
params: {id: '157201'},
headers: {
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
'X-RapidAPI-Key': '7eccf3c916msh125eb404409a0fcp1de117jsn811515176179'
}
};
axios.request(options).then(function (response) {
setfixture(response.data.response[0]);
console.log('fixturedetail '+fixturedetail.lineups[1].team.logo);
}).catch(function (error) {
console.error(error);
});
}
const renderPage = () => {
return fixturedetail ?
<ScrollView style={styles.parentview}>
<View
style={styles.leaguelogocontainer}
>
<Image
source={{uri:fixturedetail.league.logo}}
style={styles.leaguelogo}
/>
</View>
<View>
<TeamvsTeam
navigation = {navigation}
logohome={fixturedetail.teams.home.logo}
logoaway={fixturedetail.teams.away.logo}
homename={fixturedetail.teams.home.name}
awayname={fixturedetail.teams.away.name}
homescore={fixturedetail.goals.home}
awayscore={fixturedetail.goals.away}
homeid={fixturedetail.teams.home.id}
awayid={fixturedetail.teams.away.id}
/>
</View>
<Heading text="Events" />
<FlatList
data={fixturedetail.events}
horizontal={true}
renderItem={({item})=>{
return (
<EventItem
url = {item.team.logo}
name = {item.team.name}
timeelapsed = {item.time.elapsed}
extratime = {item.time.extra}
playername = {item.player.name}
asistname = {item.assist.name}
type = {item.type}
detail = {item.detail}
/>
);
}}
/>
{Lineup()}
</ScrollView>
:
<Text>Loading</Text>
}
const Lineup = () =>{
const Tab = createMaterialTopTabNavigator();
return fixturedetail.lineups.length>0 ?(
<Tab.Navigator
screenOptions ={{
tabBarStyle:{
backgroundColor:Colors.white,
borderRadius:8,
margin:16
},
tabBarLabelStyle: {
fontSize: 12,
color:Colors.black,
fontWeight:'bold',
},
}}
>
<Tab.Screen
name={fixturedetail.teams.home.name}
component={TeamLineup}
initialParams={{
index: 0,
lineup:fixturedetail.lineups
}}
/>
<Tab.Screen
name={fixturedetail.teams.away.name}
component={TeamLineup}
initialParams={{
index:1,
lineup:fixturedetail.lineups
}}
/>
</Tab.Navigator>
)
:
null;
}
return (
<View>
{renderPage()}
</View>
);
};
const styles = StyleSheet.create({
parentview:{
backgroundColor:Colors.mybackground,
width:'100%'
},
leaguelogocontainer:{
height: 150,
backgroundColor:Colors.white,
borderRadius:8,
margin:16
},
leaguelogo:{
height:'100%',
width:'auto',
minWidth:175,
alignSelf: 'center',
flexGrow:2,
alignItems: 'stretch',
flexDirection:'row'
},
});
export default FixtureDetails;
Component screen:
import React from 'react';
import {View, Text,StyleSheet,Image,FlatList } from 'react-native';
import { Colors } from './Common/Colors';
import Detail from './Common/Detail';
import Heading from './Common/Heading';
[![unable to scroll below this point][1]][1]const TeamLineup = ({route}) => {
const {index,lineup} = route.params;
console.log('logo '+lineup[index].team.logo);
return lineup.length>0 ? (
<View style={styles.parent}>
<Heading text="Lineups" />
<Image
style={styles.image}
source={{uri:lineup[index].team.logo}}
/>
<Text
style={styles.name}
>{lineup[index].team.name}</Text>
<Image
style={styles.image}
source={{uri:lineup[index].coach.photo}}
/>
<Text
style={styles.name}
>{lineup[index].coach.name}</Text>
<Text
style={styles.name}
>Team</Text>
<FlatList
style={styles.flatlist}
data={lineup[index].startXI}
renderItem={({item,index})=>{
var i = index+1;
return (
<Detail
title={i}
value={item.player.name}
/>
);
}}
/>
<Text
style={styles.name}
>Substitutes</Text>
<FlatList
style={styles.flatlist}
data={lineup[index].substitutes}
renderItem={({item,index})=>{
var i = index+1;
return (
<Detail
title={i}
value={item.player.name}
/>
);
}}
/>
</View>
): <Text>No data</Text>;
};
const styles = StyleSheet.create({
parent:{
borderRadius:8,
borderColor:Colors.black,
borderWidth:1,
backgroundColor:Colors.white,
marginHorizontal:16
},
image:{
height:100,
width:100,
alignSelf: 'center',
marginTop:16
},name:{
fontSize:24,
color:Colors.black,
alignSelf:'center',
marginTop:16
},
flatlist:{
margin:16
}
});
export default TeamLineup;

Flatlist item redirects to details page

I am new at react native and I am trying to make a detail page for my crypto price API.
What I need to do is when the user press on crypto he is redirected to a detail screen page where he can see charts, price etc. I have no idea what I should do next, I tried onpress() but it did not work. How can I make those flatList elements that are displayed using CryptoList when clicking on them shows detail page?
App.js
export default function App() {
const [data, setData] = useState([]);
const [selectedCoinData, setSelectedCoinData] = useState(null);
useEffect(() => {
const fetchMarketData = async () => {
const marketData = await getMarketData();
setData(marketData);
}
fetchMarketData();
}, [])
return (
<View style={styles.container}>
<View style={styles.titleWrap}>
<Text style={styles.largeTitle}>
Crypto
</Text>
<Divider width={1} style={styles.divider} />
</View>
<FlatList
keyExtractor={(item) => item.id}
data={data}
renderItem={({ item }) => (
<CryptoList
name={item.name}
symbol={item.symbol}
currentPrice={item.current_price}
priceChangePercentage={item.price_change_percentage_24h}
logoUrl={item.image}
/>
)}
/>
</View>
);
}
cryptoList.js
const CryptoList = ({ name, symbol, currentPrice, priceChangePercentage, logoUrl}) => {
const priceChangeColor = priceChangePercentage > 0 ? 'green' : 'red';
return (
<TouchableOpacity>
<View style={styles.itemWrapper}>
{/*Left side view*/}
<View style={styles.leftWrap}>
<Image source={{uri: logoUrl}} style={styles.image}/>
<View style={styles.titleWrapper}>
<Text style={styles.title}>{ name }</Text>
<Text style={styles.subtitle}>{ symbol.toUpperCase() }</Text>
</View>
</View>
{/*Right side view*/}
<View style={styles.rightWrap}>
<Text style={styles.title}>€{currentPrice.toLocaleString('de-DE', {currency: 'Eur'})}</Text>
<Text style={[styles.subtitle,{color: priceChangeColor} ]}>{priceChangePercentage.toFixed(2)}%</Text>
</View>
</View>
</TouchableOpacity>
)
}
import React, { useEffect, useState } from "react";
import { Text, View, StyleSheet, FlatList} from 'react-native';
import { Divider, useTheme } from 'react-native-elements';
import Constants from 'expo-constants';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { HomeScreen } from './pages/homeScreen';
// You can import from local files
import CryptoList from './components/cyproList';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import { getMarketData } from './components/cryptoApi';
const Stack = createNativeStackNavigator();
export default function App() {
const [data, setData] = useState([]);
const [selectedCoinData, setSelectedCoinData] = useState(null);
useEffect(() => {
const fetchMarketData = async () => {
const marketData = await getMarketData();
setData(marketData);
}
fetchMarketData();
}, [])
return (
<View style={styles.container}>
<View style={styles.titleWrap}>
<Text style={styles.largeTitle}>
Kriptovalūtu cenas
</Text>
<Divider width={1} style={styles.divider} />
</View>
<FlatList
keyExtractor={(item) => item.id}
data={data}
renderItem={({ item }) => (
<CryptoList
name={item.name}
symbol={item.symbol}
currentPrice={item.current_price}
priceChangePercentage={item.price_change_percentage_24h}
logoUrl={item.image}
/>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container:{
flex: 1,
backgroundColor: '#fff',
},
titleWrap:{
marginTop:50,
paddingHorizontal: 15,
},
largeTitle:{
fontSize: 22,
fontWeight: 'bold',
},
divider: {
marginTop: 10,
}
});
<!-- begin snippet: js hide: false console: true babel: false -->
<div data-snack-id="2OtINTPVy" data-snack-platform="android" data-snack-preview="true" data-snack-theme="light" style="overflow:hidden;background:#F9F9F9;border:1px solid var(--color-border);border-radius:4px;height:505px;width:100%"></div>
<script async src="https://snack.expo.dev/embed.js"></script>
your code seems incomplete. Have you tried wonPress={() => navigate(DetailsPage, {selectedCoinData})} where selectedCoinData is the details of your coin, then on details page you can retrieve the info with the params of react navigation with const route = useRoute() and use route.params.selectedCoinData
<FlatList
keyExtractor={(item) => item.id}
data={data}
renderItem={({ item }) => (
<CryptoList
name={item.name}
symbol={item.symbol}
currentPrice={item.current_price}
onPress={() => navigate(DetailsPage, {selectedCoinData})}
priceChangePercentage={item.price_change_percentage_24h}
logoUrl={item.image}
/>
)}
/>
and then in your component
const CryptoList = ({ name, symbol, currentPrice, priceChangePercentage, logoUrl, onPress}) => { return (
<TouchableOpacity onPress={onPress}>

Searchable flat list react native

I am trying to search items in a flatlist, whenever i type in the search bar it only take one letter and closes the keyboard and the value inside the search bar disappear,
example when i type "george" it only takes the letter g and re-render a list of names containing the letter g and delete what's inside the search bar
how can i fix this ?
import React, { useState, useEffect } from 'react';
import { ScrollView } from 'react-native';
import { View, Text, FlatList, ActivityIndicator, SafeAreaView, TouchableOpacity } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { Divider, SearchBar } from 'react-native-elements'
const Item = ({ name, lastName }) => (
<View>
<Text style={{ fontSize: 17, color: '#666', marginBottom: 10 }}>Full name: {name} {lastName}</Text>
</View>);
function Clients({ navigation }) {
const [isLoading, setLoading] = useState(true);
const usersApi = 'https://reqres.in/api/users'
const [users, setUsers] = useState([]);
const [search, setSearch] = useState("");
const [masterData, setMasterData] = useState("");
const fetchJson = async (userApi) => {
const response = await fetch(userApi);
return response.json()
}
useEffect(() => {
fetchJson(usersApi)
.then((users) => {
setUsers(users.data);
setMasterData(users.data);
})
.catch((error) => (alert(error)))
.finally(() => setLoading(false));
}, []);
const itemSeparator = () => {
return (
<Divider style={{ width: "105%", marginVertical: 3, alignSelf: 'center' }} />
)
}
const renderHeader = () => {
return (
<SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={text => searchFilterFunction(text)}
autoCorrect={false}
/>
);
};
const searchFilterFunction = text => {
setSearch(text);
const newData = masterData.filter(item => {
const itemData = `${item.first_name.toUpperCase()} ${item.last_name.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setUsers(newData);
};
const renderItem = ({ item }) => (
<TouchableOpacity style={{
flex: 1,
padding: 10
}}
onPress={() => { navigation.navigate('Client', { item: item }); }}
underlayColor='#ccc'
activeOpacity={0.1} >
<Item name={item.first_name} lastName={item.last_name} />
</TouchableOpacity>
);
console.log(search)
console.log(users)
return (
<SafeAreaProvider>
<SafeAreaView>
<Text style={{ color: '#666', margin: 15, fontSize: 20 }}>Clients actuels</Text>
<View style={{
width: '96%',
backgroundColor: 'white',
borderRadius: 5,
alignSelf: 'center',
marginTop: 20,
}}>
<View style={{ margin: 15 }}>
{isLoading ? <ActivityIndicator size="large" /> :
<FlatList
data={users}
renderItem={renderItem}
ItemSeparatorComponent={itemSeparator}
ListHeaderComponent={renderHeader}
keyExtractor={item => item.id.toString()}
value={search}
/>}
</View>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
export default Clients;

onPress not working in React Native Flatlist

My onPress handler is not working when someone clicks on Flatlist item.
Video of this issue
https://u.pcloud.link/publink/show?code=XZWGOUkZmDLPeKQOQJJzxnqFB8Q21X3acT7k
Here is the code:
import React, { useState, useEffect } from 'react';
import { View, Text, Image, FlatList, ActivityIndicator } from 'react-native';
import { TouchableNativeFeedback } from 'react-native-gesture-handler';
import axios from 'axios';
export default function _AjaxApp() {
const [postList, setPostList] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const loadData = (append = false) => {
let url = "https://edristi.in/wp-json/wp/v2/posts?per_page=20&page=" + currentPage;
setIsLoading(true);
setCurrentPage(currentPage + 1);
axios.get(url).then((r) => {
if (append) {
setPostList(postList.concat(r.data));
} else {
setPostList(r.data);
}
setIsLoading(false);
}).catch((e) => {
console.log(e);
});
}
useEffect(() => {
loadData();
}, [])
let Loader = <></>
if (isLoading) {
Loader = <ActivityIndicator></ActivityIndicator>
}
return (
<View>
<View style={{padding:20, backgroundColor:"#4342fe"}}>
<Text style={{color:"white"}}>Edristi App</Text>
</View>
<FlatList
data={postList}
renderItem={({ item, index, separators }) => <PostCard postList={postList} {...item} index={index} />}
keyExtractor={r => r.id + "-" + Math.random().toString()}
removeClippedSubviews={true}
maxToRenderPerBatch={2}
ListFooterComponent={Loader}
onEndReachedThreshold={0.5}
onEndReached={() => {
loadData(true);
}}
/>
</View>
);
}
class PostCard extends React.PureComponent {
onPressHandler() {
console.log("Clicked");
alert("Clicked");
}
render() {
let image = <></>
if (this.props.jetpack_featured_media_url.trim() !== "") {
image = <Image style={{ flex: 1 }} source={{
//uri: this.props.featuredimage,
uri: this.props.jetpack_featured_media_url,
}} />
}
// console.log(this.props.jetpack_featured_media_url);
return <TouchableNativeFeedback onPress={()=>{
this.onPressHandler();
}}>
<View style={{ margin: 10 }}>
<Text style={{ fontSize: 17, lineHeight: 23, fontWeight: "600" }}>{ this.props.title.rendered}</Text>
</View></TouchableNativeFeedback>
}
}
Try to import 'TouchableNativeFeedback' from 'react-native' instead of 'react-native-gesture-handler'.

I can't figure out why I keep seeing "ReferenceError: Can't find variable: val"

I'm trying to get the images inside my getImageForLogo.js to load through a loop.
That file looks like so:
const images = {
logo1: require('../assets/logo1.jpeg'),
logo2: require('../assets/logo2.png'),
'logo with space': require('../assets/logo-with-space.jpeg'),
};
export default logos => images[logos];
My App.js:
import React from 'react';
import {
StyleSheet,
View,
Image,
ScrollView,
Text
} from 'react-native';
import getImageForLogo from './utils/getImageForLogo';
import Avatar from './components/Avatar';
export default class App extends React.Component {
constructor (props) {
super(props);
this.state = {
logos: 'logo1'
};
}
render () {
const {
logos
} = this.state;
const form = { 'Logo1': 'assets/logo.jpg', 'Logo2': 'assets/logo2.jpg', 'Logo3': 'assets/logo3.jpg' };
return (
<View style={styles.appContainer}>
<View style={styles.titleContainer}>
<Text style={styles.title}>Title</Text>
</View>
<ScrollView style={styles.timerlist}>
Object.values(form).map((key, val) => (
<Avatar
initials="KC"
size={75}
key={val}
source={key}
backgroundColor={'blue'}
onPressLinkImage={() => {
console.log('Pressed!');
}}
/>
));
</ScrollView>
</View>
);
}
}
I created the const form just to try and see if the loop works. I'm trying to cycle by using:
Object.values(form).map((key, val) => (
<Avatar
initials="KC"
size={75}
key={val}
source={key}
backgroundColor={'blue'}
onPressLinkImage={() => {
console.log('Pressed!');
}}
/>
));
however, when I run this, the app crashes and says ReferenceError: Can't find variable: val. I can't figure out why this happens because if I run this code on the Chrome terminal, it works.
EDIT:
Here's Avatar.js:
import {
ColorPropType,
StyleSheet,
Text,
View,
Image,
TouchableOpacity
} from 'react-native';
import PropTypes from 'prop-types';
import React from 'react';
import getImageForLogo from '../utils/getImageForLogo';
export default function Avatar({
size,
backgroundColor,
initials,
source,
onPressLinkImage,
}) {
const style = {
width: size,
height: size,
borderRadius: size / 2,
backgroundColor,
};
const image = getImageForLogo(source)
return (
<View style={[styles.container, style]}>
<TouchableOpacity onPress={onPressLinkImage}>
<Image source={image} style={styles.image} />
</TouchableOpacity>
</View>
);
}
Avatar.propTypes = {
initials: PropTypes.string.isRequired,
size: PropTypes.number.isRequired,
source: PropTypes.string.isRequired,
backgroundColor: ColorPropType.isRequired,
onPressLinkImage: PropTypes.func.isRequired,
};
Your code in the App.js appears to be missing some { } around your Object.values.
So instead of putting inside your ScrollView
Object.values(form).map((key, val) => (
<Avatar
initials="KC"
size={75}
key={val}
source={key}
backgroundColor={'blue'}
onPressLinkImage={() => {
console.log('Pressed!');
}}
/>
)
);
you should put
{Object.values(form).map((key, val) => (
<Avatar
initials="KC"
size={75}
key={val}
source={key}
backgroundColor={'blue'}
onPressLinkImage={() => {
console.log('Pressed!');
}}
/>
)
)}
notice that it is contained inside the { }.
Here is it inside your App.js
import React from 'react';
import {
StyleSheet,
View,
Image,
ScrollView,
Text
} from 'react-native';
import getImageForLogo from './utils/getImageForLogo';
import Avatar from './components/Avatar';
export default class App extends React.Component {
constructor (props) {
super(props);
this.state = {
logos: 'logo1'
};
}
render () {
const {
logos
} = this.state;
const form = { 'Logo1': 'assets/logo.jpg', 'Logo2': 'assets/logo2.jpg', 'Logo3': 'assets/logo3.jpg' };
return (
<View style={styles.appContainer}>
<View style={styles.titleContainer}>
<Text style={styles.title}>Title</Text>
</View>
<ScrollView style={styles.timerlist}>
{Object.values(form).map((key, val) => (
<Avatar
initials="KC"
size={75}
key={val}
source={key}
backgroundColor={'blue'}
onPressLinkImage={() => {
console.log('Pressed!');
}}
/>
))}
</ScrollView>
</View>
);
}
}
Also note your Object.values(form).map((key, val) will give the following keys and values
key | val
assets/logo.jpg | 0
assets/logo1.jpg | 1
assets/logo2.jpg | 2
For readability of your code I would change your code to the following:
{Object.values(form).map((source, key) => (
<Avatar
initials="KC"
size={75}
key={key}
source={source}
backgroundColor={'blue'}
onPressLinkImage={() => {
console.log('Pressed!');
}}
/>
)
)}