I am trying to fetch posts from a Wordpress API including image sources and then display them in Snap Carousel, However images are not displaying while the text is displayed and images is getting undefined.
Here is the code, the URL i have removed for now.
Everything seems to be working fine, only the images are not loading.
import React, { Component } from 'react';
import { Text, View, Button, Image, flex } from 'react-native';
import Icon from 'react-native-vector-icons/Feather';
import Carousel from 'react-native-snap-carousel';
class HomeSlider extends Component{
constructor(props){
super(props);
this.state = {
activeIndex:0,
posts: {},
loading: true,
}
}
componentDidMount(){
fetch("https://#/wp-json/wp/v2/posts?per_page=4")
.then((response) => response.json())
.then((data => {
this.setState({
posts: data,
loading: false,
})
}
))
}
renderItem({item,index}){
return (
<View style={{
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
borderRadius: 20,
height: 250,
marginLeft: 16,
backgroundColor: 'white',
elevation: 20,
marginBottom:20,
marginTop: 20,
shadowColor: 'white',
shadowOffset: {
width: 0,
height: 10,
},
shadowOpacity: 0.58,
shadowRadius: 16.00,
display: flex, flexDirection: 'column'}}>
<Image style={{height: 150, width: '100%' ,borderTopLeftRadius: 20,
borderTopRightRadius: 20}}
source={{uri: item.illustration}} />
<Text style={{fontSize: 14, padding: 12 ,marginTop: 20, fontFamily: 'poppins_semibold'}}>{item.title}</Text>
</View>
)
}
render(){
if(this.state.loading){
return(<View><Text>Loading</Text></View>)
}else{
const carouselItems = this.state.posts.map(function(x){
return (
{
title: x.title.rendered,
illustration: x.better_featured_image.source_url,
}
)
})
return(
<View style={{ flex: 1, flexDirection:'row', marginTop: 20, backgroundColor: '#FBFEFB'}}>
<Carousel
loop={true}
loopClonesPerSide={2}
autoplay={true}
autoplayDelay={200}
autoplayInterval={15000}
layout={"default"}
ref={ref => this.carousel = ref}
data={carouselItems}
sliderWidth={100}
itemWidth={350}
renderItem={this.renderItem}
onSnapToItem = { index => this.setState({activeIndex:index}) } />
</View>
)
}
}
}
export default HomeSlider;
Looks perfect!
Just checked in below code whether illustration is giving you the correct URL.
const carouselItems = this.state.posts.map(function(x){
return (
{
title: x.title.rendered,
illustration: x.better_featured_image.source_url, // test here by placing dummy url.
}
)
})
Related
i've done the react-native-pdf to show the slides of my pdf file. But, I want to set the current page state to show up on the display. And when the value is set, it'll refresh that screen and goes back to the first page automatically.
this is my code:
import React, { useState } from 'react';
import { StyleSheet, Dimensions, View, Text } from 'react-native';
import Pdf from 'react-native-pdf';
function Work() {
const [currentPage, setCurrentPage] = useState()
const ShowPdf = () => {
const source = { uri: 'http://samples.leanpub.com/thereactnativebook-sample.pdf', cache: true };
return (
<Pdf
source={source}
onLoadComplete={(numberOfPages, filePath) => {
console.log(`number of pages: ${numberOfPages}`);
}}
onPageChanged={(page, numberOfPages) => {
console.log(`current page: ${page}`);
setCurrentPage(page) //set the cuurentPage
}}
onError={(error) => {
console.log(error);
}}
onPressLink={(uri) => {
console.log(`Link presse: ${uri}`)
}}
style={styles.pdf} />
)
}
return (
<View style={styles.container}>
<ShowPdf />
<View style={styles.pageNumber}>
<Text>{currentPage}</Text>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
//marginTop: 25,
//backgroundColor: 'red',
backfaceVisibility: 'hidden'
},
pdf: {
flex: 1,
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
pageNumber: {
position: 'absolute',
left: 20,
top: 20,
backgroundColor: 'rgba(173, 173, 173, 0.5)',
padding: 13,
borderRadius: 6,
}
});
export default Work;
my emulator display:
image
Anyway I can fix this?
Instead of use this
<View style={styles.container}>
<ShowPdf />
<View style={styles.pageNumber}>
<Text>{currentPage}</Text>
</View>
</View>
please use it
<View style={styles.container}>
<Pdf
source={{ uri: path }}
onLoadComplete={(numberOfPages, filePath) => {
console.log(`number of pages: ${numberOfPages}`);
}}
onPageChanged={(page, numberOfPages) => {
console.log(`current page: ${page}`);
setCurrentPage(page) //set the cuurentPage
}}
onError={(error) => {
console.log(error);
}}
onPressLink={(uri) => {
console.log(`Link presse: ${uri}`)
}}
style={styles.pdf} />
<View style={styles.pageNumber}>
<Text>{currentPage}</Text>
</View>
</View>
<ShowPdf/> is your custom react component it will be re-rendered for every page change. So, that is why you faced this problem
I'm trying to style my renderItem in FlatList but elevation not working properly. Is there anything I'm wrong or this is a React Native issue?
I tested ListView too but it still not working properly
This is TodoItem component
import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'
const styles = StyleSheet.create({
container: {
height: 60,
backgroundColor: 'white',
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 2, height: 2 },
shadowOpacity: 0.4,
shadowRadius: 2,
elevation: 3,
justifyContent: 'center',
paddingHorizontal: 30,
marginBottom: 12
},
text: {
fontSize: 18,
fontWeight: '400',
color: '#080808'
}
})
export default class TodoItem extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.text}> {this.props.text} </Text>
</View>
)
}
}
And this is where I call it in FlatList
<FlatList
data={this.props.items}
renderItem={(item) => <TodoItem key={item.index} text={item.item} />}
/>
The point is that elevation works properly if I don't use FlatList like this
<TodoItem text="Hello world" />
What I excepted
What I see
Most issues like this are caused by styling that is applied to your surrounding view or the row that you are trying to render.
If you add a marginHorizontal: 10 to the styles.container for the row that should probably do it for you.
Here is a simplified example where the edges of the row are not cut off. It has a couple of tweaks to make it work, using state.items instead of props.items and changing the style name for the TodoItem to itemContainer. It should give you an idea of how to implement it.
import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
state = {
items: [
'Hello'
]
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.items}
renderItem={(item) => <TodoItem key={item.index} text={item.item} />}
/>
</View>
);
}
}
class TodoItem extends React.Component {
render() {
return (
<View style={styles.itemContainer}>
<Text style={styles.text}> {this.props.text} </Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight + 10,
backgroundColor: '#ecf0f1',
},
itemContainer: {
marginHorizontal: 10,
height: 60,
backgroundColor: 'white',
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 2, height: 2 },
shadowOpacity: 0.4,
shadowRadius: 2,
elevation: 3,
justifyContent: 'center',
paddingHorizontal: 30,
marginBottom: 12
},
text: {
fontSize: 18,
fontWeight: '400',
color: '#080808'
}
});
Here is a snack showing it working https://snack.expo.io/#andypandy/flatlist-with-elevation-on-rows
I am using a custom component with image and text. The image is relative to the text. Please see the screenshot.
image 1
image 2.
I have used the TouchableOpacity component as root view for that.
In screenshots when long press on the component, two views are overlapping with shadow. It looks ugly when long press.
Please see the code below for reusable component.
'use strict';
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Image,
} from 'react-native';
export default class ExampleButton extends Component {
constructor (props) {
super (props);
}
_handleOnPress = () => {
console.log('pressed!!!');
};
render () {
console.log (this.props);
return (
<TouchableOpacity
onPress={this.handleOnPress}
>
<View style={styles.btnCompContainer}>
<View
style={{
backgroundColor: '#FFF',
justifyContent: 'center',
borderRadius: 30,
height: 50,
width: '100%',
}}
>
<Text style={styles.btnTxt}>{this.props.buttonText}</Text>
</View>
<View style={[styles.btnElmContainer]}>
<Image
style={[{height: 30, width: 30,resizeMode:'stretch'}]}
source={this.props.image}
/>
</View>
</View>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create ({
btnCompContainer: {
flexDirection: 'row',
alignItems: 'center',
height: 60,
marginLeft: 10,
marginRight: 20,
},
btnElmContainer: {
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
width: 60,
height: 60,
backgroundColor:'#fff',
borderRadius: 30,
shadowColor: '#000000',
shadowOffset: {
width: 1,
height: 1,
},
elevation:5,
shadowRadius: 2,
shadowOpacity: 0.3,
},
btnTxt: {
marginLeft: 80,
color: '#9e9e9e',
fontSize: 16,
fontWeight: 'bold',
textAlign: 'left',
},
});
Here I am using this reusable component in code.
'use strict';
import React, {Component} from 'react';
import {
Animated,
StyleSheet,
Text,
TextInput,
View,
Image,
ImageBackground,
TouchableOpacity,
Button,
StatusBar,
Easing
} from 'react-native';
// Custom Components
const searchBGImg = require('../assets/search-bg-kit.png');
const houseLogo = require('../Resources/house.png');
import ExampleButton from './components/common/example-button';
export default class TypeSelect extends Component<Props> {
// Navigation Option
static navigationOptions = {
header: null
}
constructor() {
super();
this.state = {
visible: false,
x: new Animated.Value(-100),
};
}
slide = () => {
Animated.spring(this.state.x, {
toValue: 0,
easing: Easing.easeOutBack
}).start();
this.setState({
visible: true,
});
};
gotoSearch = () =>{
this.props.navigation.navigate('DocSearch')
}
componentDidMount(){
this.slide();
}
render() {
return (
<View style={styles.container}>
<ImageBackground source={searchBGImg} style={styles.imgBG}>
<View style={{alignItems:'center', marginBottom:20}}>
<Image style={{height:57, width:69, marginBottom:12}} source={houseLogo} />
</View>
<View>
<Animated.View
style={[styles.slideView, {
transform: [
{
translateX: this.state.x
}
]
}]}>
<ExampleButton image={houseLogo} buttonText={'Click here'} />
<ExampleButton image={houseLogo} buttonText={'Click here'} />
</Animated.View>
</View>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
imgBG:{
flex: 1,
flexDirection: "column",
justifyContent:"center",
width: "100%",
height: "100%"
}
})
It is working fine in iOS, but it's not working in android up to the mark. Please help me to work it in android.
Thanks in advance.
You should use renderToHardwareTextureAndroid prop on <View /> component.
In your example like this:
<View style={styles.btnCompContainer} renderToHardwareTextureAndroid >
<View
style={{
backgroundColor: '#FFF',
justifyContent: 'center',
borderRadius: 30,
height: 50,
width: '100%',
}}
>
<Text style={styles.btnTxt}>{this.props.buttonText}</Text>
</View>
<View style={[styles.btnElmContainer]}>
<Image
style={[{height: 30, width: 30,resizeMode:'stretch'}]}
source={this.props.image}
/>
</View>
</View>
I am using react-native-camera for video capture. I am building something kind of snapchat stories where moment you capture video next to that it takes you to the preview screen of video where you can edit. On press of start button while videoCapturing screen it returns path of the video but on press of stop button it returns an error at the same time making video to get stored to my device storgae. I have posted both videocapturing screen as well error I am getting on press of stop button.Attached code for the VideoCapture screen.
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,Dimensions,Image,TouchableOpacity,TouchableHighlight,Video
} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
import { TabNavigator, StackNavigator } from 'react-navigation';
import Icon from 'react-native-vector-icons/Ionicons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import Camera from 'react-native-camera';
export default class VideoCapture extends Component {
static navigationOptions = {
headerTintColor: 'white',
headerStyle:{ position: 'absolute', backgroundColor: 'transparent', zIndex: 100, top: 0, left: 0, right: 0 }
};
constructor(props) {
super(props);
this.state = {
cameraType : 'back',
mirrorMode : false,
path: null,
};
}
takeVid() {
const option = {};
this.camera.capture({
mode: Camera.constants.CaptureMode.video
})
.then((data) => {
console.log(data);
this.setState({ path: data.path })
})
.catch((err) => console.error(err));
}
stopVid(){
this.camera.stopCapture();
}
changeCameraType() {
if(this.state.cameraType === 'back') {
this.setState({
cameraType : 'front',
mirrorMode : true
})
}
else {
this.setState({
cameraType : 'back',
mirrorMode : false
})
}
}
renderCamera() {
return (
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}
type={this.state.cameraType}
captureMode = {Camera.constants.CaptureMode.video}
mirrorImage={this.state.mirrorMode}
keepAwake={true}
>
<Text style={styles.capture} onPress={this.changeCameraType.bind(this)}>switch</Text>
<View style={styles.textCircular}><Text style={{color:'#fefefe',fontSize:14}} onPress={this.takeVid.bind(this)}>Start</Text></View>
<View style={styles.textCircular1}><Text style={{color:'#fefefe',fontSize:14}} onPress={this.stopVid.bind(this)}>Stop</Text></View>
</Camera>
);
}
renderVideo() {
return (
<View>
<Video source={{ uri: this.state.path }}
style={styles.preview}
rate={1.0}
volume={1.0}
muted={false}
resizeMode={"cover"}
onEnd={() => { console.log('Done!') }}
repeat={true}
/>
<Text
style={styles.cancel}
onPress={() => this.setState({ path: null })}
>Cancel
</Text>
</View>
);
}
render() {
const {goBack} = this.props.navigation;
return (
<View style={styles.container}>
{this.state.path ? this.renderVideo() : this.renderCamera()}
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
width: 70,
height: 70,
borderRadius: 35,
borderWidth: 5,
borderColor: '#FFF',
marginBottom: 15,
},
cancel: {
position: 'absolute',
right: 20,
top: 20,
backgroundColor: 'transparent',
color: '#FFF',
fontWeight: '600',
fontSize: 17,
}
});
I have a simple tabbar app.
One of the tabs renders a view where I display pictures fetched remotely.
The issue I'm facing is, whenever I switch tabs, the images are re-displayed, despite the fact than neider render is called again, nor shouldComponentUpdate.
This results in a very bad user experience as the view is refreshed over and over again.
Any idea of how I can fix it?
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TabBarIOS,
ScrollView,
Image,
Dimensions
} from 'react-native';
var {height, width} = Dimensions.get('window');
class TabIssue extends Component {
constructor(props){
super(props);
this.state = {
selectedTab: 'tab1',
items: []
}
}
componentDidMount() {
// Build an array of 60 photos
let items = Array.apply(null, Array(60)).map((v, i) => {
return { id: i, src: 'http://placehold.it/200x200?text='+(i+1) }
});
this.setState({ items });
}
render() {
return (
<TabBarIOS>
<TabBarIOS.Item title="Tab #1"
selected={this.state.selectedTab === 'tab1'}
onPress={() => {
this.setState({ selectedTab: 'tab1', });
}}>
<View style={{marginTop: 20}}>
<Text> toto</Text>
</View>
</TabBarIOS.Item>
<TabBarIOS.Item title="Tab #2"
selected={this.state.selectedTab === 'tab2'}
onPress={() => {
this.setState({ selectedTab: 'tab2', });
}}>
<ScrollView>
<View style={styles.galleryContainer}>
{
this.state.items.map((item) => {
return(
<View key={item.id} style={styles.pictureContainer}>
<Image source={{uri: item.src}} style={styles.picture} />
</View>
)
})
}
</View>
</ScrollView>
</TabBarIOS.Item>
</TabBarIOS>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
galleryContainer: {
flexWrap: 'wrap',
flexDirection: 'row',
flex: 1,
backgroundColor: 'red'
},
picture: {
height: width/2 - 4,
width: width/2 -4,
flex: 1,
},
pictureContainer: {
padding: 2
}
});
AppRegistry.registerComponent('TabIssue', () => TabIssue);