Skip to content

Instantly share code, notes, and snippets.

@quartarian
Last active February 20, 2022 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save quartarian/e4a022978e447e3a4980922e38c3dda1 to your computer and use it in GitHub Desktop.
Save quartarian/e4a022978e447e3a4980922e38c3dda1 to your computer and use it in GitHub Desktop.
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