Posts component in React

This is the fourth part of Create react app with GraphQL way of WordPress data

In this part, we will develop Posts component at src/components/Posts.js

First, we import the Link component from react-router-dom and DomPurify from dompurify package.

import { Link } from "react-router-dom";
import DOMPurify from "dompurify";

First, declare excerpt as

excerpt = this.props.post.node.excerpt;

Now, in return, we create a link. The link component of react-router-dom creates link.

<Link to={`/post/${this.props.post.node.id}`}>
  <h2
    dangerouslySetInnerHTML={{
      __html: DOMPurify.sanitize(this.props.post.node.title)
    }}
  />
</Link>

Then render excerpt as

<article>
  <p
  dangerouslySetInnerHTML={{
    __html: DOMPurify.sanitize(
       this.excerpt.slice(0, this.excerpt.indexOf("Continue reading"))
    )
  }}
  />
</article>

Finally, src/components/Posts.js full codes are

import React from "react";
import { Link } from "react-router-dom";
import DOMPurify from "dompurify";

class Posts extends React.Component {
  excerpt = this.props.post.node.excerpt;

  render() {
    return (
      <div>
        <Link to={`/post/${this.props.post.node.id}`}>
          <h2
            dangerouslySetInnerHTML={{
              __html: DOMPurify.sanitize(this.props.post.node.title)
            }}
          />
        </Link>
        <article>
          <p
            dangerouslySetInnerHTML={{
              __html: DOMPurify.sanitize(
                this.excerpt.slice(0, this.excerpt.indexOf("Continue reading"))
              )
            }}
          />
        </article>
      </div>
    );
  }
}
export default Posts;

At now, our app is like this

Leave a Reply

Your email address will not be published. Required fields are marked *