npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

wordpress-posts-react

v1.4.0

Published

React hooks and components to asynchronously fetch and display WordPress posts using its most updated API

Downloads

3

Readme

Supertype     wordpress-posts-react     npm     github | wordpress-posts-react     license

WordPress-Posts-React

A lightweight (<3 kb minified!) set of React hooks and components to asynchronously fetch and display WordPress posts using WordPress's most updated REST API.

Why?

Almost all of the other WordPress React libraries I found were either too bloated or too old and unmaintained, which uses outdated mechanisms to retrieve blog articles off WordPress sites. This library is designed to be as lightweight as possible (no dependencies), and provides drop-in components to display posts in a variety of ways directly in your React app.

Installation

You can install the package using yarn or npm:

yarn add wordpress-posts-react
# or
npm install wordpress-posts-react

This will install wordpress-posts-react from the npm registry and add it to your package.json file.

Usage

Common Patterns

The most common pattern is to use the useWordPressFeed hook to fetch posts from a WordPress site, and then use the WordPressBlogroll component to render the posts as a blogroll. The following snippet demonstrates that:

import { WordPressBlogroll, useWordPressFeed } from 'wordpress-posts-react'

const Blogroll = () => {

    const { feed, loading } = useWordPressFeed('https://supertype.ai')

    if(!loading){
    return (
        <main>
            <div>
                <h1>{feed.length} Articles</h1>
                <WordPressBlogroll feed={feed} />
            </div>
        </main>
    )}
    else{
        return <div>Loading...</div>
    }
}

This will fetch the latest 10 posts from the WordPress site at https://supertype.ai and render a beautifully formatted blogroll in your React or Next.js app.

It uses WordPress' officially documented REST API to fetch the posts, so it will always be up to date with the latest WordPress features, returns JSON data (yay! no XML!), ⚡ fast, and with almost no 🚧 maintenance required. Weighing at less than 10kb, it's also 🪶 featherweight, with no dependencies.

  • 🎁 Beautifully formatted blogroll
  • 📅 Human-friendly dates (e.g. "2 days ago")
  • 💨 Uses async and await to fetch posts asynchronously
  • 🚀 Uses WordPress's official REST API to fetch posts
  • 📦 No dependencies (Less than 10kb in size)

Hooks and Components

useWordPressFeed(site_url, author_id, number_of_posts = 10) is a React hook that asynchronously fetches posts from a WordPress site and returns the posts as an array of objects. Only its first argument is required: the URL of the WordPress site you want to fetch posts from.

  • author_id: If specified, this narrows down to WordPress posts of the author you want to fetch posts from. If you don't pass in an author_id, it will fetch posts from all authors.
  • number_of_posts: The number of posts you want to fetch. Defaults to 10.

💡 Pro tip: To confirm that the site is in fact a WordPress site, you can append /wp-json to your site (e.g <your-site>/wp-json/) and see if it returns a JSON object. If it does, then you can be sure that the site is a WordPress site. This is the same mechanism that wordpress-posts-react uses to fetch and render the Wordpress posts as an isolated React component.

import { useWordPressFeed } from 'wordpress-posts-react'

// fetches author id=23's latest 10 posts from https://supertype.ai
useWordPressFeed('https://supertype.ai', 23)

// fetches author id=17's latest 5 posts from https://supertype.ai
useWordPressFeed('https://supertype.ai', 17, 5)

WordPressBlogroll({ feed }) is a React component that renders a blogroll of posts. It takes in a feed prop, which is an array of objects that contain the post's title, date, excerpt, and link. Usually used in conjunction with useWordPressFeed to fetch posts from a WordPress site.

import { useWordPressFeed, WordPressBlogroll } from 'wordpress-posts-react'

const { feed, loading } = useWordPressFeed('https://supertype.ai')
{
    !loading &&
        <WordPressBlogroll feed={feed} />
}

There are also a few utility functions that you can use to format dates, parse HTML and decode HTML entities. You are not required to directly use them in your React project, as they are used internally by wordpress-posts-react to format the posts. However, they are exported so you can use them elsewhere in your own React application or roll your own blog components (e.g <YourOwnCustomBlogRoll />) after cleaning the returned json data using these utility functions.

import { useWordPressFeed, timeAgo, 
         parseUrlString, decodeHtml } 
from 'wordpress-posts-react'

const BlogComponent = ({url}) => {
    const { wp_data, loading } = useWordPressFeed(url)
    const [feed, setFeed] = useState([]);

    useEffect(() => {
        if(wp_data && !loading){
            const posts = wp_data.map((post) => {
                const { title, link, date, excerpt } = post;
                    return {
                        id: post.id,
                        title: decodeHtml(title.rendered),
                        link: parseUrlString(link),
                        date: timeAgo(date),
                        excerpt: decodeHtml(excerpt.rendered),
                        // ...other custom attributes post-cleansing
                    };
                });
            setFeed(posts);
        }
    }, [url]);

    return <YourOwnCustomBlogRoll feed={feed} />
    
}

Development

This package uses Rollup to bundle the library. To build it, run with either:

yarn build
# or
npm run build

To do this in watch mode, run:

yarn start
# or
npm run start

Please feel free to open an issue or submit a pull request if you have any questions or suggestions!