Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kl-Rahul's avatar

how to get single post data from wordpress rest api to react using axios

I'm using the following to fetch a single post from the WordPress REST API.

    import React, { Component } from 'react';
    import axios from 'axios';

 class Pages extends Component {
 constructor() {
       super();
          this.state = {
               post: [],
            };
         }

     componentDidMount() { 
          axios.get('http://localhost:8080/tapline/index.php/wp-json/wp/v2/pages/2')
             .then(response => {
                 this.setState({ post: response.data });
        })
.catch(error => {
    console.log(error);
    
});
}

  render() {
  return (
 
       <div>
             {this.state.post.map(single => {
                return(
                  <div>
                    <h1 >{single.title.rendered}</h1>
                  </div>                                        
                   );
              })}
          </div>
          );
        }
     }

   export default Pages;

Is there a better/more straightforward way to render the post without mapping an array? or how to render single post data

0 likes
6 replies
Kl-Rahul's avatar

@folium Hi thanks for reply

For this any another way?

B'coz m work on like this way let me know this is correct?

 const ids = [274];
     axios.get(`http://112/training/wp-json/wp/v2/pages?${ids.map(id => 
    `include[]=${id}`).join("&")}`)
1 like
folium's avatar

@Kl-Rahul i think this will help you out mapping ids...

  {employees.map((employee) => (
    <li key={employee.id} onClick={() => handleClick(employee.id)}>
        {employee.name}
    </li>
))}
const handleClick = (employeeId) => {
    axios.get(`http://localhost:5050/employees/${employeeId}`).then((res) => {
        setEmployees(res.data);
    });
};
2 likes
Kl-Rahul's avatar

@folium Nice! this is right

One mor question How can i get API name in href tag

I can get {single.post_name} in the href tag ?

 render() {
     return (
          <>
           <ul className="navbar-nav mr-auto">
                        {
                            this.state.matrixmenu
                                .map(single =>
                                    <li className="nav-item">
                                    const name = 
                                     <Link className="nav-link" to="/{single.post_name} ">{single.title}</Link>
                                   </li>
                                )
                            }
                        </ul>
           </>
     )
 }
1 like
folium's avatar

@Kl-Rahul Means ??

How can i get API name in href tag

what you trying to say. ??

Please or to participate in this conversation.