Coder Social home page Coder Social logo

mreckendonk / react-wordpress-comments Goto Github PK

View Code? Open in Web Editor NEW

This project forked from karen-sarkisyan/react-wordpress-comments

2.0 0.0 0.0 628 KB

A react component for headless WordPress that fetches and publishes comments via REST API

License: MIT License

TypeScript 91.81% CSS 8.19%

react-wordpress-comments's Introduction

react-wordpress-comments

WordPress-powered comments for React frontend

npm

Easily add comments to your headless WordPress with react-wordpress-comments component.

Here's a working demo, where you can even check it out. Even with your own WordPress endpoint. Comment posting works, so be careful :)

react-wordpress-comments uses native WordPress REST API, so you don't need any additional configuration in most cases.

Using is as simple as this:

<WpComments
  maxDepth={3}
  pageId={619}
  hostUrl="https://your-wp-site.com"
  allowComments={true}
  user={john}
/>

It's an alpha version. See ongoing development section for more information.

Features

  • Native WordPress API. No need to use any plugins for WordPress, component uses WP's built-in REST API.
  • Lazy loading. Fetches comments after the component is mounted to the DOM.
  • Tree structure. Shows comments in hierarchical tree with custom depth.
  • Submit comments. Users can submit comments, including responses to other comments. You may need to enable anonymous comments via REST API if you want users to comment without authorization. This component does not have a basic auth functionality, but you can provide user data with JWT.
  • Validation before submit. Submit form uses native HTML validation to check fields.
  • Authentication. If your frontend uses JWT to authorize users, you can pass this user data for comment posting.

Prerequisites

  • A WordPress website with public REST API.

  • react 16.8 or higher as a peer dependency.

๐Ÿš€ Installation and usage

  1. Install package in your repository with a React app:
npm install react-wordpress-comments
  1. Import it along with React and use it:
import React from "react"
import WpComments from "react-wordpress-comments"
import "react-wordpress-comments/css/styles.css"

function MyComponent() {
  return (
    <div>
      <h1>This is my page's title</h1>
      <p>Here goes the main content of the page</p>
      <WpComments
        maxDepth={3} // provide depth that you want comments to be nested in a list
        pageId={619} // id of a page you want to fetch comments from and post to
        hostUrl="https://wordpress.example.com" // url of your WordPress website
        allowComments={true} // can users post comments?
        user={user} // provide user if authorized, default is null. See below
      />
    </div>
  )
}

render(<MyComponent />, document.querySelector("#root"))

Translations (optional)

To override default strings pass an object to translationOverrides prop of the Component.

Object structure is like this:

type Translations = {
  mainHeading?: string
  leaveCommentHeading?: string
  loadingCommentsLabel?: string
  respondLinkLabel?: string
  loggedInUserIntro?: string
  nameInputLabel?: string
  emailInputLabel?: string
  commentInputLabel?: string
  commentInputPlaceholder?: string
  submitButtonLabel?: string
  cancelLinkLabel?: string
  commentsClosedNotice?: string
}

User and authentication (optional)

user prop is an object that should look like this:

let user = {
  name: "Maria",
  email: "[email protected]",
  jwt: "jwt-string-value",
}

name and email properties are required.

If you authenticate users in your React app, you're probably providing user info via Context API.

If that is the case, you can construct an object with user name, email, and JWT string to pass down to comments section. The component will automatically send Authorization header with Bearer: "jwt-string-value" when posting the comment.

Note that by default WordPress does not support JWT. You will need a plugin for that.

Known limitations

Number of comments fetched

The component will load only 100 comments from an API. Pagination is a feature that is yet to come.

Authorization

By default there are two ways to submit comments โ€” either anonymously, or authenticated-only. In order to have some sort of combined logic (anonymous or authorized for those who can be authorized) you need to implement it in WordPress.

To allow anonymous posting of comments via REST API you need to add a code snippet to your WordPress. Read more here on Stackoverflow.

Cross-origin resource sharing

When we use decoupled architecture, the requests are cross-origin.

WP REST API allows CORS by default. However, your server configuration might be set differently, and it would prevent comments from being posted and/or fetched. If you receive CORS errors, you may need to manually add headers that allow all origins, or use a plugin. For more security, allow only one origin where your front end lives. However, allowing origin in headers is not the only thing that may prevent your browser to make a CORS request, you may need to configure your server or browser.

Rest API endpoint url

By default comments are fetched from {your-wp-host}/wp-json/wp/v2/comments endpoint.

If you're using non-pretty permalinks, your REST API endpoint URL may be different from standard, in this case the component won't work. As of now the only way to change it is to change the source code of the component.

Alternative way to use this component

Simply copy the content from src/ folder of this repo and drop it into your React app's src/components/wpComments folder (or whatever structure you use). Then simply import it like you would any other component you've written. Don't forget to grab /css/styles.css file too if you need it.

Styling

The package has a styles.css file that provides some basic styles and a loader spinner. If you import it along with the component like this:

import "react-wordpress-comments/css/styles.css"

It uses very minimal styling, most of its look will be inherited so that the comments match overall style of your page. You can override styles by using more specific selectors. (See demo app for example.)

Otherwise use your own stylesheet without importing component's styles at all.

Ongoing development

Upgrades, features and bugfixes to come:

  • Error boundaries and better error handling. At this point the component may crash your app if there is an error โ˜น๏ธ
  • Tests and CI automation
  • Links processing. If you don't specify your frontend host in WordPress, the links within comments will point to your backend host.
  • Pagination

Contributing

If you have a feedback or suggestion, just file an issue. Anything is welcome.

To contribute to code, see contributing guide. But really, if you want to contribute, just do it :)

License

Licensed under the MIT License.

react-wordpress-comments's People

Contributors

karen-sarkisyan avatar

Stargazers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.