Armin Ganji
Armin Ganji

Reputation: 43

How to get Id from postlist(posts.js) and show on post.js page in react native

I'm getting a list of news through api wordpress and displaying posts.js. Now I want to go to the 1post.js page by clicking on each item and displaying that particular item.

componentDidMount(){
return fetch('URL/wp/api/get_posts')
    .then( (response) => response.json() )
    .then( (responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson.posts,
      })             
    })
    .catch((error)=> {
    });     
} render() { if (this.state.isLoading){ return ( ) } else{ let posts=this.state.dataSource.map((val, key) => { return {val.title} }); return ( {posts} );

Upvotes: 0

Views: 234

Answers (1)

Hamza Waleed
Hamza Waleed

Reputation: 1462

To navigate from one component to another, you need to create a navigation container. react-navigation is the official module for navigating between components. Visit this link to create a stack navigator and then you can use below code to achieve the above said.

async componentDidMount() {
    fetch('URL/wp/api/get_posts')
    .then(res => res.json())
    .then(data => this.setState({posts: data }))
}

renderPostList(){
    return this.state.posts.map(post=>(
        <TouchableOpacity onPress={this.props.navigation.navigate("NextScreen",{selectedPost:post})}>
            <Text>{post.title}</Text>
        </TouchableOpacity>
    ))
}
render() {

    return (
        <View>
            {this.renderPostList()}
        </View>
    )
}

Upvotes: 1

Related Questions