Reputation: 141
I'm trying to get the titles and featured images from several pages that are included in a JSON response. After searching for a while and trying something, I'm getting stuck on displaying the required elements. The code on the React Native side looks like this:
https://snack.expo.io/@jvdl2711/artists
I found a way to display my data in the desired order and style. Unfortunately, each 'post' should be clickable to navigate to other screens and visualize those individual posts, but I don't know how because the objects are rendered different than expected at the moment. Is there any way how to solve this?
Upvotes: 0
Views: 1592
Reputation: 11
if (!defined('ABSPATH')) {
die("You cannot access this website!!!");}
function react_customizer_rest_api_init(){
register_rest_field('post', 'featured_src', ['get_callback' =>'react_customizer_get_featured_img',]);}
add_action('rest_api_init', 'react_customizer_rest_api_init');
register_activation_hook(__FILE__, 'react_customizer_plugin_activate');
Now you can see a new field 'featured_src' in your code. use this to display the image of a post.
Upvotes: 0
Reputation: 427
The problem with your approach is that you're are not iterating your data.
So to create the wanted behaviour you need to use something similar to this (you need to fix the style according to your specs):
(I've added a loading indicator and a simple error handling to this example, also you need to add a default image cause I've noticed some items with no thumbs)
import React, {Component} from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
Image,
ActivityIndicator,
} from 'react-native';
export default class Home extends Component {
state = {
data: [],
isLoading: true,
isError: false,
}
componentWillMount() {
fetch('http://54.168.73.151/wp-json/wp/v2/pages?parent=38&per_page=100')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson,
isLoading: false,
isError: false
})
})
.catch((error) => {
this.setState({
isLoading: false,
isError: true
})
console.error(error);
});
}
renderRow = (item) => (
<View>
<Image
style={styles.thumb}
source={{uri: item.better_featured_image ? item.better_featured_image.source_url : 'url to a default image'}}
/>
<Text style={styles.title}>{item.title.rendered}</Text>
</View>
)
getKey = (item) => String(item.id)
renderComponent() {
if (this.state.isLoading) {
return (
<ActivityIndicator/>
)
} else if (this.state.isError) {
return (
<Text>Error loading data</Text>
)
} else {
return (
<FlatList
data={this.state.data}
renderItem={({item}) => this.renderRow(item)}
keyExtractor={this.getKey}
/>
)
}
}
render() {
return (
<View style={styles.container}>
{this.renderComponent()}
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
thumb: {
height: 100,
width: 100,
resizeMode: 'cover',
},
})
Upvotes: 3