I can access the points using http requests to the external api, but I
need to be able to access the full api inside of the react-wp-theme.
You could use either the wp-api
script / Backbone JavaScript client library or one of the other client libraries listed here such as the node-wpapi
library.
Using the wp-api
script
-
Enqueue the script:
wp_enqueue_script( 'wp-api' );
-
In
index.php
, make sure<?php wp_head(); ?>
is added in the documenthead
, and<?php wp_footer(); ?>
in thebody
.
And then in your React components, access the client via window.wp.api
instead of just wp.api
:
const postsCollection = new window.wp.api.collections.Posts(); // like this
//const postsCollection = new wp.api.collections.Posts(); // not this
Here’s an example React Component which uses the Posts
collection to retrieve one post: (the markup is based on your Post
component)
import React from "react";
class Post extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
item: {}
};
}
componentDidMount() {
// Instantiates the collection.
const postsCollection = new window.wp.api.collections.Posts();
// Retrieves one post.
postsCollection.fetch({ data: { per_page: 1 } })
.done(posts => {
this.setState({
isLoaded: true,
item: posts[0]
});
})
.error((xhr, status, error) => {
this.setState({
isLoaded: true,
error
});
});
}
render() {
const { error, isLoaded, item } = this.state;
if (error || item.errors) {
return <div>Error: {error || 'API error...'}</div>;
} else if (! isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="container indigo lighten-4">
<div className="container flow-text py-5 mt-5">
<h3>{item.title.rendered}</h3>
<p>{item.excerpt.rendered}</p>
</div>
</div>
);
}
}
}
export default Post;
Tried and tested working, and the code is based on the official example.
Using the node-wpapi
library
You can refer to the documentation on installing the library and using it.
But here’s the above Post
component, adapted to using the node-wpapi
library: (the ...
means nothing changed)
import React from "react";
const WPAPI = require('wpapi');
const wp = new WPAPI({
endpoint: 'http://example.com/wp-json'
});
class Post extends React.Component {
constructor(props) {
...
}
componentDidMount() {
// Retrieves one post.
wp.posts().perPage(1)
.then(posts => {
this.setState({
isLoaded: true,
item: posts[0]
});
})
.catch(err => {
this.setState({
isLoaded: true,
error: err.message
});
});
}
render() {
...
}
}
export default Post;
The Full Code
You can check my files here.