I tried following this tutorial to get a feel of how dynamic routing would work. Now instead of using static data, I want to pull in blog posts using WordPress' API to generate unique links for each post. I'm able to generate the link, but none of the data is generating on the new page. What am I doing wrong here?
Articles.js (serves as the preview page to grab all the blog posts, works as expected)
import React, { Component } from 'react';
import { Link, Route } from 'react-router-dom';
import Article from './Article';
const newsURL = "http://myprivateblogapi.com/wp-json/wp/v2/posts?_embed";
export default class Articles extends Component {
constructor(props) {
super(props);
this.state = {
newsData: [],
requestFailed: false
} }
componentDidMount() {
fetch(newsURL)
.then(response => {
if(!response.ok) {
throw Error("Network request failed.");
}
return response
})
.then(d => d.json())
.then(d => {
this.setState({
newsData: d
})
}, () => {
this.setState({
requestFailed: true
})
}) }
render() {
let articles = this.state.newsData.map((article, index) => {
if(this.state.requestFailed) return <p>Failed!</p>
if(!this.state.newsData) return <p>Loading...</p>
return(
<div key={index} className="article-container">
<div className="article-preview">
<span className="article-date">{article.date}</span>
<h5>{article.title.rendered}</h5>
<div dangerouslySetInnerHTML={{ __html: article.excerpt.rendered }} />
<Link to={`/news/${article.slug}`}>Read More...</Link>
</div>
<Route path={`/news/:articleSlug`}
render={ (props) => <Article data={articles} {...props} />} />
</div>
)
});
return (
<div>
<h3>All Articles from Blog</h3>
{articles}
</div>
) } }
Article.js (to render up each individual article)
import React from 'react';
const Article = ({match, data}) => {
let article = data.find(a => a.slug == match.params.articleSlug);
let articleData;
if(article)
articleData = <div>
<h3> {article.title.rendered}</h3>
{ console.log(`${article.title.rendered}`) }
<p>{article.content.rendered}</p>
{ console.log(`${article.content.rendered}`) }
<hr />
</div>
else
articleData = <h2> Sorry. That article doesn't exist. </h2>;
return (
<div>
<div>
{articleData}
</div>
</div>
)
}
export default Article;