DEV Community

loading...
Cover image for Integrate WordPress rest Api in Reactjs

Integrate WordPress rest Api in Reactjs

mohsinalisoomro profile image MOHSIN ALI SOOMRO ・2 min read

Hi There Hope you are fine
Demo here

I will integrate rest API in react js using JWT authentication for that you need a plugin to install in your WordPress and active it.
JWT Auth — WordPress JSON Web Token Authentication.
WordPress JSON Web Token Authentication allows you to do REST API authentication via a token. It is simple, non-complex, and easy to use. This plugin probably is the most convenient way to do JWT Authentication in WordPress.
by useful team

The react app is integrated with wp rest API and crud operation on the posts
steps

1: Open the .htaccess file in the root folder of WordPress and paste

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
Enter fullscreen mode Exit fullscreen mode

2: Open the wp-config.php file in the root folder of WordPress and paste

get the secret key from the given link or you put your own
link

define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
define('JWT_AUTH_CORS_ENABLE', true);
Enter fullscreen mode Exit fullscreen mode

Now you get endpoint for authentication
http://yourdomain.com/wp-json/jwt-auth/v1/token

Using axios

Promise based HTTP client for the browser and node.js

const loginData = {
            username: "Username",
            password: "Password"
        };
axios.post('http://yourdomain/wp-json/jwt-auth/v1/token', loginData)
    .then((res) => {
        console.log(res.data);
        localStorage.setItem('token', res.data.token);
        localStorage.setItem('user_nicename', res.data.user_nicename);
        localStorage.setItem('user_email', res.data.user_email);
        localStorage.setItem('user_display_name', res.data.user_display_name);
    })
    .catch((err) => {
        console.log(err);
    });
Enter fullscreen mode Exit fullscreen mode

Crud Operation Endpoint for posts

Get All post (get all post you does not need any token)
http://yourdomain.com/wp-json/wp/v2/posts

axios.get('http://yourdomain/wp-json/wp/v2/posts')
    .then((res) => {
        console.log(res.data)   
    })
    .catch((err) => {
        console.log(err);
});
Enter fullscreen mode Exit fullscreen mode

Create a post (You need an authentication token from login)
http://yourdomain.com/wp-json/wp/v2/posts

const formdata = {
    title: title,
    content: content,
    status: 'publish'
};

axios.post('http://yourdomain/wp-json/wp/v2/posts', formdata, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
    })
    .then((res) => {
        console.log(res);           
    })
    .catch((err) => {
        console.log(err)
});
Enter fullscreen mode Exit fullscreen mode

Edit Post (You need an authentication token from login)
http://yourdomain.com/wp-json/wp/v2/posts/id

const formdata = {
    title: title,
    content: content,
    status: 'publish'
};
axios.post('http://yourdomain/wp-json/wp/v2/posts/'+id, formdata, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
    })
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(res);
});
Enter fullscreen mode Exit fullscreen mode

Delete Post (You need authentication token from login)
http://yourdomain.com/wp-json/wp/v2/posts/id

axios.delete('http://yourdomain/wp-json/wp/v2/posts/' + id, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
    })
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
});
Enter fullscreen mode Exit fullscreen mode

For code here is the GitHub link
code

If there is any difficulty feel free to comment I will reply to you asap

Thanks for ready if this will helpful for you then comments and star my repo

Discussion (3)

pic
Editor guide
Collapse
dance2die profile image
Sung M. Kim

Hi there Mohsin.

Would you format the code snippets?
You could check out the editor guide for documentation :)

Collapse
mohsinalisoomro profile image
MOHSIN ALI SOOMRO Author

Thank you Sung M. Kim for providing the documentation guidelines

Collapse
dance2die profile image
Sung M. Kim

yw and thank you for taking time to making it better~