Forked from quartarian/gist:e4a022978e447e3a4980922e38c3dda1
Created
February 20, 2022 08:13
-
-
Save MerlinOfCode/c921101d92dd68d4c78e7306faac0c3e to your computer and use it in GitHub Desktop.
React - Wordpress Page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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