Home > Software engineering >  How to display data fetched from Wordpress RestAPI in html format using React?
How to display data fetched from Wordpress RestAPI in html format using React?

Time:11-30

Using React, I am trying to get page data from a WordPress API. pic of my current output

As you can see, the date and title data are displayed normally but the excerpt is not rendered properly. I am not sure how I can fix that. Below is the code I use to fetch and display the data:

To fetch the data:

//fetching the pages
  useEffect( ()=>{
    Axios.get("https://www.eswaran.no/wp-json/wp/v2/pages").
    then(response => {
      setPosts(response.data);
      
    }, [posts, setPosts]);
})

To display the data:

<div className="page-list">
      {posts && posts.length && posts.map((post, index) => {
          return (
            <div key={post.id} className="page">
              <h2>{post.title.rendered}</h2>
              <h4>{moment(post.date).format('Do MMMM YYYY')}</h4>
              <div dangerouslySetInnerHTML={{  __html: post.excerpt.rendered}}  />
              <a href={post.link} target="_blank">Go to page</a>
            </div>
          );
        })}
</div>

CodePudding user response:

Ok your Api is well returning the data.

So in order to just remove the brackets, you can use regex :

  {posts && posts.length && posts.map((post, index) => {
      const cleanExcerpt = post.excerpt.rendered.replace(/\[([^\[])*(\])/g, '');

      return (
        <div key={post.id} className="page">
          <h2>{post.title.rendered}</h2>
          <h4>{moment(post.date).format('Do MMMM YYYY')}</h4>
          <div dangerouslySetInnerHTML={{  __html: cleanExcerpt }}  />
          <a href={post.link} target="_blank">Go to page</a>
        </div>
      );
    })}
  • Related