Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display data fetched from WordPress RestAPI in html format using React?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//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>

>Solution :

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>
      );
    })}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading