Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React - Wordpress Page
import React from 'react';
import $ from "jquery";
class WpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading:true,
path: this.props.location.pathname
};
this.fetchPage(this.props.location.pathname);
}
componentDidUpdate = (prevProps) => {
if(prevProps.location.pathname != this.props.location.pathname) {
this.setState({
isLoading:true,
path: this.props.location.pathname
});
this.fetchPage(this.props.location.pathname);
}
}
fetchPage = (slug) => {
$.ajax( {
url: 'https://www.site.com/wp-json/'
+ 'wp/v2/pages/?slug='
+ slug,
method: 'GET'
} ).done( ( response ) => {
if(typeof response[0] === "undefined") {
this.setState({
isLoading:false,
title: "404: Page Not Found",
content: ""
});
}
else {
this.setState({
isLoading:false,
title: response[0].title.rendered,
content: response[0].content.rendered
});
}
})
}
render() {
if(this.state.isLoading) return(<div>Loading...</div>);
return(
<div className="wp-page">
<h1 dangerouslySetInnerHTML={{__html: this.state.title}} />
<div dangerouslySetInnerHTML={{__html: this.state.content}} />
</div>
);
}
}
export default WpPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.