react-native-swiper does not show dynamic images - reactjs

I have issue that my swiper does not show images. Swiper and dots from swiper are there but images are not showing. I am pretty new to react-native. This is my code:
import React from 'react';
import {
StyleSheet,
View,
Image,
Text
} from 'react-native';
import Swiper from 'react-native-swiper';
export default class HomeScreen extends React.Component {
state = {
data: []
}
componentDidMount = () => {
this.setState({
data: this.props.navigation.getParam('data', 'NO-DATA')
});
}
render() {
return (
<View style={styles.container}>
<Swiper
style = {styles.swiper }
>
{
this.state.data.map( (item, i) => {
<View>
<Text> {item.url} </Text>
<Image
style={{width: 200, height: 200}}
source={{uri: item.url}}
/>
</View>
})
}
</Swiper>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'red',
alignItems: 'center',
justifyContent: 'center',
},
swiper: {
width: 200,
height: 200
}
});
The issue is not only with image, also it is happening with text, etc.
Am i missing something ?

Return is missing inside the map add it.
{
this.state.data.map && this.state.data.map( (item, i) => {
return(
<View>
<Text> {item.url} </Text>
<Image
style={{width: 200, height: 200}}
source={{uri: item.url}}
/>
</View>)
})
}
Or without return. If you use ( this bracket you no need to add return
{
this.state.data.map && this.state.data.map( (item, i) => (
<View>
<Text> {item.url} </Text>
<Image
style={{width: 200, height: 200}}
source={{uri: item.url}}
/>
</View>)
))
}

Related

Make the Header scroll down with FlatList and Animated - React Native

I didn't find any soulotion to do animated with FlatList,
I want to hide my Header when I scroll down like In Facebook app.
I tried To use FlatList with diffClamp() without success,
I don't know if I can do it with FlatList but I need also LazyLoading,
Someone Can help me?
This is my Header:
import React, { useState } from "react";
import {
View,
Animated,
Text,
Dimensions,
TouchableOpacity
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "#expo/vector-icons";
const Header = props => {
const params = props.scene.route.params;
const [headerHeight] = useState(
params !== undefined && params.changingHeight !== undefined
? params.changingHeight
: Dimensions.get("window").height * 0.065
);
return (
<SafeAreaView style={{ backgroundColor: "rgb(152,53,349)" }}>
<Animated.View
style={{
width: Dimensions.get("window").width,
height: headerHeight,
flexDirection: "row",
backgroundColor: "rgb(152,53,349)"
}}
>
<TouchableOpacity
onPress={() => {
props.navigation.openDrawer();
}}
>
<View
style={{
paddingVertical: "15%",
justifyContent: "center",
paddingHorizontal: 25
}}
>
<Ionicons name="ios-menu" size={30} color={"white"} />
</View>
</TouchableOpacity>
<View style={{ justifyContent: "center", marginLeft: "23%" }}>
<Text
style={{
fontSize: 20,
fontWeight: "bold",
textAlign: "center",
color: "white"
}}
>
MyGameenter code here{" "}
</Text>
</View>
</Animated.View>
</SafeAreaView>
);
};
export default Header;
This is my FlatLIst:
import React from "react";
import { View, FlatList, StyleSheet } from "react-native";
import { EVENTS } from "../data/dummy-data";
import Event from "./Event";
const renderGridItem = itemData => {
return <Event item={itemData.item} />;
};
const ShowEvents = props => {
return (
<View style={styles.list}>
<FlatList
keyExtractor={(item, index) => item.id}
data={EVENTS}
renderItem={renderGridItem}
numColumns={1}
/>
</View>
);
};
const styles = StyleSheet.create({
list: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
export default ShowEvents;
Use
onScroll={(e) => console.log(e.nativeEvent.contentOffset.y)}
Working Example: https://snack.expo.io/#msbot01/privileged-candies
import React, { Component } from 'react';
import { Text, View, StyleSheet, ScrollView, FlatList } from 'react-native';
import Constants from 'expo-constants';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
DATA: [],
previous: 0,
hide: false,
};
}
componentDidMount() {
var array = [];
for (var i = 0; i < 100; i++) {
var a = { id: i, value: i };
array.push(a);
}
this.setData(array);
}
setData(a) {
this.setState({
DATA: a,
});
}
Item({ title }) {
return (
<View
style={{
width: '100%',
height: 30,
marginTop: 5,
backgroundColor: 'green',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text />
</View>
);
}
_onScroll(event) {
// console.log('>>>>>>>>>>>'+this.state.data);
if (this.state.previous < event) {
this.setState({
hide: true,
previous: event,
});
} else {
this.setState({
hide: false,
previous: event,
});
}
console.log(event);
}
render() {
return (
<View style={{ flex: 1 }}>
{this.state.hide == true ? null : (
<View
style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>Hide me while scrolling</Text>
</View>
)}
<FlatList
onScroll={e => this._onScroll(e.nativeEvent.contentOffset.y)}
data={this.state.DATA}
renderItem={({ item }) => (
<View
style={{
width: '100%',
height: 30,
marginTop: 5,
backgroundColor: 'green',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text />
</View>
)}
keyExtractor={item => item.id}
/>
</View>
);
}
}
const styles = StyleSheet.create({});
import React, { useState } from "react";
import { View, FlatList, StyleSheet, Platform, Dimensions } from "react-native";
import { EVENTS } from "../data/dummy-data";
import Event from "./Event";
const HeaderHeight = () => {
if (Platform.OS === "android" && Dimensions.get("window").height < 600)
return Dimensions.get("window").height * 0.075 + 20;
else if (Platform.OS === "android")
return Dimensions.get("window").height * 0.058 + 20;
else return Dimensions.get("window").height * 0.01 + 20;
};
const renderGridItem = itemData => {
return <Event item={itemData.item} />;
};
const ShowEvents = props => {
const [previous, SetPrevious] = useState(false);
const [hide, SetHide] = useState(false);
_onScroll = event => {
const headerHeight = HeaderHeight();
if (event > headerHeight) {
SetHide(true);
props.navigation.setParams({
hide: true
});
SetPrevious(event);
} else if (event < 0.1) {
SetHide(false);
props.navigation.setParams({
hide: false
});
SetPrevious(event);
}
};
return (
<View style={styles.list}>
<FlatList
onScroll={e => _onScroll(e.nativeEvent.contentOffset.y)}
keyExtractor={(item, index) => item.id}
data={EVENTS}
renderItem={renderGridItem}
numColumns={1}
/>
</View>
);
};
const styles = StyleSheet.create({
list: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
export default ShowEvents;

react native scrollview showing up on down part of the emulator

I am trying to create a scroll view in react native.
I gave full-device-width and height for the scroll-view.
width is working but height is not working so the app is showing only on down part of the emulator,
I would like to know how can I make this showing up in fullscreen and also why this error occurring.
this is how it's loading on emulator.
you can find my react-native code below
import React, { Component } from 'react';
// import Counterpart from './Counterpart'
import contacts from './contacts'
import {
View,
Button,
ScrollView,
Switch,
Text,
Input,
StyleSheet,
Dimensions,
} from 'react-native';
const widthfull = Dimensions.get('window').width; //full width
const heightfull = Dimensions.get('window').height; //full height
const styles = StyleSheet.create({
mainwrap: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
zIndex:1,
},
countfont: {
fontSize: 120,
},
marginfromtop: {
display: 'flex',
flex: 1,
paddingTop: 50,
},
ScrollViewstles: {
display: 'flex',
flex: 1,
margin:0,
padding:0,
zIndex:2,
width:widthfull,
height:heightfull,
paddingLeft:30
}
});
export default class App extends Component {
state = {
showCounter: true
}
toggglecounter = () => {
this.setState(() => ({showCounter: !this.state.showCounter}))
}
render() {
if (this.state.showCounter) {
return (
<View style={styles.mainwrap}>
<View style={[styles.marginfromtop, styles.countfont]}>
<Button
style={{ marginTop: 50 }}
onPress={this.toggglecounter}
title="Toggle Contacts"
/>
</View>
<View style={styles.mainwrap}>
<ScrollView style={styles.ScrollViewstles}>
{contacts.map(c => (
<Text key={c.key}>{c.name}</Text>
))}
</ScrollView>
</View>
</View>
);
} else {
return (
<View style={[styles.marginfromtop, styles.countfont]}>
<Button
style={{ marginTop: 50 }}
onPress={this.toggglecounter}
title="Toggle Contacts"
/>
</View>
);
}
}
}
remove flex: 1 from marginfromtop
marginfromtop: {
paddingTop: 50,
},

React Native Add Top thin header

hello I'm developing a react native app everything is fine but I have a problem
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
<StatusBar
translucent={true}
backgroundColor={'rgba(0, 0, 0, 0.3)'}
barStyle={'light-content'}
/>
{ this.gradient }
<ScrollView
style={styles.scrollview}
scrollEventThrottle={200}
directionalLockEnabled={true}
>
{ carousel }
<FlatList
data={ this.state.GridListItems }
renderItem={ ({item}) =>
<TouchableOpacity
style={styles.GridViewContainer}
onPress={() => this.props.navigation.push('ProfileScreen', { height: "6'2", category: item.key })}>
<ImageBackground
source={{ uri: item.img }}
style={{width: '108%', height: '110%', justifyContent:'center'}}
>
<Text style={styles.GridViewTextLayout} > {item.key} </Text>
</ImageBackground>
</TouchableOpacity>
}
numColumns={2}
/>
</ScrollView>
</View>
</SafeAreaView>
);
styles
safeArea: {
flex: 1,
backgroundColor: colors.black
},
container: {
flex: 1,
backgroundColor: colors.background1
},
when I scroll down you see the mobile battery and wifi (top bar) is in the app
I want the app to be below the mobile topbar how can I achieve that?
here is an expo qr code
once try this and let me know your results:
import React,{Fragment} from 'react';
return (
<Fragment>
<SafeAreaView style={{ flex: 0, backgroundColor: 'red' }} />
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
{ this.gradient }
<ScrollView
style={styles.scrollview}
scrollEventThrottle={200}
directionalLockEnabled={true}
>
{ carousel }
<FlatList
data={ this.state.GridListItems }
renderItem={ ({item}) =>
<TouchableOpacity
style={styles.GridViewContainer}
onPress={() => this.props.navigation.push('ProfileScreen', { height: "6'2", category: item.key })}>
<ImageBackground
source={{ uri: item.img }}
style={{width: '108%', height: '110%', justifyContent:'center'}}
>
<Text style={styles.GridViewTextLayout} > {item.key} </Text>
</ImageBackground>
</TouchableOpacity>
}
numColumns={2}
/>
</ScrollView>
</View>
</SafeAreaView>
);
i added safeareaview (flex:0) for statusBar you can apply any color you want.
provide options in your navigator file as:
navigationName: {
screen: fileName,
navigationOptions: ({ navigation }) => {
if (Platform.OS === "android") {
return {
title: 'images',
headerStyle: {
backgroundColor: '#382464',
height: 50,
},
headerTitleStyle: {
color: '#fff',
},
headerTintColor: '#fff',
// header: props => <UriBar {...props} />
}
} else {
return {
header: null
}
}
}
},
you can also use statusBar for android
You should use SafeAreaView.
It will render your component without overlapping the "top bar".
import { SafeAreaView } from 'react-native'
...
return (
<SafeAreaView>
// your components
<SafeAreaView/>
)
Edit:
As you can see in the docs.
Simply wrap your top level view with a SafeAreaView with a flex: 1 style applied to it. You may also want to use a background color that matches your application's design.
So if you already using SafeAreaView, maybe you don't have flex: 1 and it's not working in the way you want.

React Native Modal not showing up

I am trying to show a modal without going to another screen, I want it to be displayed on the current screen but not through navigation. The modal doesn't pop up and I don't know the problem.
I am using the renderModal to show the modal on the screen.When I use this.props.navigation.navigate('AnotherModal'), it works but goes to another screen,this time I want to show modal on the same screen.
import * as React from 'react';
import { Text, View, Image,
StyleSheet,Alert,Modal,TouchableHighlight } from 'react-native';
import { Constants } from 'expo';
import { Appbar, Colors, FAB } from 'react-native-paper';
import ProductsModal from './ProductsModal';
import ModalTester from './ModalTester';
export default class AppBar extends React.Component {
state = {
modalVisible: false,
};
setModalVisible(visible)
{
this.setState({modalVisible: visible});
}
renderModal() {
return (
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={{marginTop: 22}}>
<View>
<Text>Hello World!</Text>
<TouchableHighlight
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
);
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.appbar}>
<Appbar style={styles.piece}>
<Appbar.Action
icon={require('../../assets/devices.png')}
onPress={this.renderModal.bind(this)}
/>
</Appbar>
<View>
<Image
source={require('../../assets/cutout.png')}
style={styles.cutout}
pointerEvents="none"
/>
<FAB
icon={require('../../assets/add_circle.png')}
color="#b2beb5"
onPress={() => navigate('Homes')}
style={styles.fab} />
</View>
<Appbar style={[styles.piece, styles.right]}>
<Appbar.Action
icon={require('../../assets/account_box.png')}
onPress={() => console.log('Account pressed')}
/>
</Appbar>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
//backgroundColor: '#ecf0f1',
padding: 8,
},
appbar: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
height: 56,
flexDirection: 'row',
},
piece: {
flex: 1,
backgroundColor: Colors.grey300,
},
right: {
justifyContent: 'flex-end',
},
cutout: {
height: 56,
width: 80,
tintColor: Colors.grey300,
},
fab: {
position: 'absolute',
margin: 12,
bottom: 16
}
});
You should try to bind your setModalVisible in the constructor first:
constructor(props) {
super(props);
this. setModalVisible = this. setModalVisible.bind(this);
}
And then change your first Appbar.Action to something like this:
<Appbar.Action
icon={require('../../assets/devices.png')}
onPress={() => this. setModalVisible(true)}
/>
Also you have to add your Modal to the rendered code
...
<Appbar.Action
icon={require('../../assets/account_box.png')}
onPress={() => console.log('Account pressed')}
/>
</Appbar>
{this.renderModal()}
</View>
I'm not sure the bind is necessary though
Since screen does not change, your Modal needs to be within the render method of that screen. This means it can be handled by the state of the component. For example to show it you can:
<Appbar.Action
icon={require('../../assets/devices.png')}
onPress={() => this.setModalVisible(true)}
/>
In the main render you can just add directly your renderModal, 'cause its visible prop is sufficient to handle the behavior:
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.appbar}>
<Appbar style={styles.piece}>
<Appbar.Action
icon={require('../../assets/devices.png')}
onPress={this.renderModal.bind(this)}
/>
</Appbar>
<View>
{this.renderModal()}
<Image
source={require('../../assets/cutout.png')}
style={styles.cutout}
pointerEvents="none"
/>
<FAB
icon={require('../../assets/add_circle.png')}
color="#b2beb5"
onPress={() => navigate('Homes')}
style={styles.fab} />
</View>
<Appbar style={[styles.piece, styles.right]}>
<Appbar.Action
icon={require('../../assets/account_box.png')}
onPress={() => console.log('Account pressed')}
/>
</Appbar>
</View>
);
}

how to add keys in this project

im using react o nexpo xde and when i run the project i get a warning because my list doesnt hae keys, i want to know where and how to assing them, this is my code
import React, { Component } from 'react';
import { StyleSheet, Text, View,AppRegistry,Image,ActivityIndicator, FlatList,Navigator,TouchableHighlight, } from 'react-native';
import { StackNavigator } from 'react-navigation';
class Lista extends Component {
static navigationOptions = {
title: 'Lista',
}
constructor(props) {
super(props);
this.state = {
data:[]
};
}
load = async ()=>{
try{
let resp = await fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=fd829ddc49214efb935920463668608d')
let json = await resp.json()
this.setState({data:json.articles})
} catch (err) { console.log(err) }
}
componentDidMount(){this.load()}
render() {
return (
<View style={{ flex: 1}}>
<View style={{ flex:1,backgroundColor:'gray'}}>
<FlatList
data={this.state.data}
renderItem={({item}) => (
<TouchableHighlight onPress={() => this.props.navigation.navigate('Details', {item})}>
<View style={{ height:100,margin:15,backgroundColor:'skyblue', padding: 10, flexDirection: 'row'}}>
{item.urlToImage !== null &&
<Image source={{uri:item.urlToImage}} style={{width: 90, height: 80 }}/>
}
<View style={{ flex: 1 }}>
<Text style={{ textAlign: 'center',fontWeight: 'bold', fontSize: 18, color: 'white', flex:1, margin:10}}>{item.title}</Text>
<Text style={{ textAlign: 'right',fontWeight: 'bold', fontSize: 11, color: 'white'}}>{item.publishedAt}</Text>
</View>
</View>
</TouchableHighlight>
)}
/>
</View>
</View>
);
}
}
class DetailsScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const { item } = navigation.state;
return {
title: item ? item.date : 'Details Screen',
}
};
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Image source={{uri:this.props.navigation.state.params.item.urlToImage}} style={{width: 90, height: 80 }}/>
<Text>{this.props.navigation.state.params.item.title}</Text>
<Text>{this.props.navigation.state.params.item.publishedAt}</Text>
</View>
);
}
}
const RootStack = StackNavigator(
{
Lista: {
screen: Lista,
},
Details: {
screen: DetailsScreen,
},
},
{
initialRouteName: 'Lista',
}
);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
i know it has to be something like, key={i} bu i hae tried in some ways and it doesnt work, im just learning react by myself so im a little confused here
ty so much
In your case you need to set up key to each child of <FlatList /> component. By react native docs recomended to use keyExtractor method defined in your component.
keyExtractor = (item, index) => index
render() {
return (
<View style={{ flex: 1}}>
<View style={{ flex:1,backgroundColor:'gray'}}>
<FlatList
data={this.state.data}
keyExtractor={this.keyExtractor}
renderItem={({item}) => (
<TouchableHighlight onPress={() => this.props.navigation.navigate('Details', {item})}>
<View style={{ height:100,margin:15,backgroundColor:'skyblue', padding: 10, flexDirection: 'row'}}>
{item.urlToImage !== null &&
<Image source={{uri:item.urlToImage}} style={{width: 90, height: 80 }}/>
}
<View style={{ flex: 1 }}>
<Text style= {{ textAlign: 'center',fontWeight: 'bold', fontSize: 18, color: 'white', flex:1, margin:10}}>{item.title}</Text>
<Text style= {{ textAlign: 'right',fontWeight: 'bold', fontSize: 11, color: 'white'}}>{item.publishedAt}</Text>
</View>
</View>
</TouchableHighlight>
)}
/>
</View>
</View>
);
}
I set just index of element as key, but you can set as you wont, but make sure it is unique. But using indexes is bad practice, it is not safe.

Resources