Git Product home page Git Product logo

wp-reactivate's Introduction

alt-text

WP Reactivate

WP Reactivate is a React boilerplate built specifically for WordPress, allowing you to quickly and easily integrate React into your WordPress plugins.

⚠️Since the release of Block Editor (Gutenberg) the Javascript ecosystem around WordPress has evolved rapidly. This repository, does not represent the best practices that should be used for React development in the WordPress.⚠️

Setup and installation

Usage

  • Install required modules: yarn (or npm install)
  • Build development version of app and watch for changes: yarn build (or npm run build)
  • Build production version of app:yarn prod (or npm run prod)

Quick Start

Introduction

This boilerplate plugin provides three different WordPress views in which an independant React app can be rendered:

  • Shortcode
  • Widget
  • Settings page in the backend (wp-admin)

Each JavaScript root file will correspond to the independant React app to be bundled by Webpack.

webpack.config.js

entry: {
  'js/admin': path.resolve(__dirname, 'app/admin.js'),
  'js/shortcode': path.resolve(__dirname, 'app/shortcode.js'),
  'js/widget': path.resolve(__dirname, 'app/widget.js'),
},

Using the Shortcode

In order to get the shortcode attributes into our Javascript we need to pass them to an object which will be made available to the shortcode.js app via wp_localize_script. Be careful with the security of data you pass here as this will be output in a <script> tag in the rendered html.

includes/Shortcode.php

public function shortcode( $atts ) {
  wp_enqueue_script( $this->plugin_slug . '-shortcode-script' );
  wp_enqueue_style( $this->plugin_slug . '-shortcode-style' );

  $object_name = 'wpr_object_' . uniqid();

  $object = shortcode_atts( array(
    'title'       => 'Hello world',
    'api_nonce'   => wp_create_nonce( 'wp_rest' ),
    'api_url'	  => rest_url( 'wp-reactivate/v1/' ),
  ), $atts, 'wp-reactivate' );

  wp_localize_script( $this->plugin_slug . '-shortcode-script', $object_name, $object );

  $shortcode = '<div class="wp-reactivate-shortcode" data-object-id="' . $object_name . '"></div>';
  return $shortcode;
}

You can access the shortcode attributes via the wpObject prop which is passed into your React container component.

app/containers/Shortcode.jsx

import React, { Component } from 'react';

export default class Shortcode extends Component {
  render() {
    return (
      <div className="wrap">
        <h1>WP Reactivate Frontend</h1>
        <p>Title: {this.props.wpObject.title}</p>
      </div>
    );
  }
}

Using the Widget

In order to get the widget options into our Javascript we need to pass them to an object which will be made available to the widget.js app via wp_localize_script. Be careful with the security of data you pass here as this will be output in a <script> tag in the rendered html.

includes/Widget.php

public function widget( $args, $instance ) {
  wp_enqueue_script( $this->plugin_slug . '-widget-script', plugins_url( 'assets/js/widget.js', dirname( __FILE__ ) ), array( 'jquery' ), $this->version );
  wp_enqueue_style( $this->plugin_slug . '-widget-style', plugins_url( 'assets/css/widget.css', dirname( __FILE__ ) ), $this->version );

  $object_name = 'wpr_object_' . uniqid();

  $object = array(
    'title'       => $instance['title'],
    'api_nonce'   => wp_create_nonce( 'wp_rest' ),
    'api_url'	  => rest_url( 'wp-reactivate/v1/' ),
  );

  wp_localize_script( $this->plugin_slug . '-widget-script', $object_name, $object );

  echo $args['before_widget'];

  ?><div class="wp-reactivate-widget" data-object-id="<?php echo $object_name ?>"></div><?php

  echo $args['after_widget'];
}

You can access the widget options via the wpObject prop which is passed into your React container component.

app/containers/Widget.jsx

import React, { Component } from 'react';

export default class Widget extends Component {
  render() {
    return (
      <div className="wrap">
        <h1>WP Reactivate Widget</h1>
        <p>Title: {this.props.wpObject.title}</p>
      </div>
    );
  }
}

Using REST Controllers

We have included a single base REST controller class in the plugin. You will need to use this controller to create endpoints to interact with your React components. Depending on the complexity of your plugin you may need to have multiple controllers or may want to extend default WordPress REST API endpoints.

We have chosen the custom controller approach for its control and flexibility. Please see the WordPress developer documentation on adding custom endpoints and specifically the controller pattern to familiarise your with our choice of implementation.

It is important to become well versed in using the WordPress REST API as this is how you will be passing data to and from your React applications.

Using the Settings Page

In our admin class we add a sub menu page to the Settings menu using add_options_page and render the React Admin container onto the root DOM node.

includes/Admin.php

public function display_plugin_admin_page() {
 ?><div id="wp-reactivate-admin"></div><?php
}

Using fetchWP

We have provided a utility class called fetchWP which is a simple abstraction over the Fetch API which allows you to easily make requests to the WordPress REST API.

In the React container component we show how to retrieve and update this setting via the example REST controller included in the boilerplate.

First we initialise fetchWP in the ES6 class constructor of our container component. It requires two parameters being the REST URL and the REST nonce which can be supplied from our wpObject.

app/containers/Admin.jsx

  constructor(props) {
    super(props);

    this.state = {
      example_setting: '',
    };

    this.fetchWP = new fetchWP({
      restURL: this.props.wpObject.api_url,
      restNonce: this.props.wpObject.api_nonce,
    });

    this.getSetting();
  }

In the getSetting call you can now see how we use the utility to perform a GET request on the 'example' endpoint.

app/containers/Admin.jsx

  getSetting = () => {
    this.fetchWP.get( 'example' )
    .then(
      (json) => this.setState({
        example_setting: json.value,
        saved_example_setting: json.value
      }),
      (err) => console.log( 'error', err )
    );
  };

We have found this utility covers most of our use cases. If you are looking for something more full featured (especially if you are working with standard WP endpoints) then have a look at node-wpapi.

Technologies

Tech Description
React A JavaScript library for building user interfaces.
Babel Compiles next generation JS features to ES5. Enjoy the new version of JavaScript, today.
Webpack For bundling our JavaScript assets.
ESLint Pluggable linting utility for JavaScript and JSX

The boilerplate has been updated to use PHP namespaces and autoloading. Please see Tom McFarlin's article on the subject if you are not familiar.

Tutorials

Building a WordPress plugin with React - Part 1, Part 2

Credits

Made by Pangolin

wp-reactivate's People

Contributors

dependabot[bot] avatar dnusca avatar ionofzion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wp-reactivate's Issues

Moving Plugin From Admin Settings to its own Admin Menu Item

Hi awesome plugin this has been such a huge help for some projects that I have been working on. The only issue that I am having is when trying to move the plugin out from a sub item under Settings to its own admin menu item. Any ideas on how to go about this? Your help would be greatly appreciated thanks!

React widget not updating with code changes

#Hi,

When I change the code the for widget, it doesn't update it when I refresh the page. For example when I add a react component to the widget view and refresh the page, there are no changes. Even when I add plan html there are no changes.

I rebuild the project but no luck. Any ideas?

EDIT: -----
It was an issue with another part of my setup

routing

Hi there,

Sorry if I'm asking something obvious. I'm a newbie to working with wordpress.

There is nothing about routing in the documentation or setup. Can you guys elaborate on that a bit?

For example let's say my plugin is loaded at /myplugin (http://my-site-url.com/myplugin) by wordpress. And the sub-routes of /myplugin is handled by react-router e.g. /myplugin/myroute1 (http://site-url.com/myplugin/myroute1) or /myplugin/myroute2 (http://site-url.com/myplugin/myroute2) etc which works fine (for me without an issue using react-router-dom project).

However, wordpress yields "OOPS! THAT PAGE CAN’T BE FOUND." when I try to load the site directly with a subroute in the address bar e.g. http://site-url.com/myplugin/myroute2.

Thanks.

Heavy prod .js file

My app folder weights 110Kb, however the final shortcode.js file is almost 700Kb.
I have tried source-map-explorer in order to analyze the prod files. But the analysis doesn't give anything. I suspect for the following reason described in the package page:

"For source-map-explorer to be useful, you need to generate a source map which maps positions in your minified file all the way back to the files from which they came.
If you use browserify, you can generate a JavaScript file with an inline source map using the --debug flag:
browserify -r .:foo --debug -o foo.bundle.js
source-map-explorer foo.bundle.js"

How can I lower the weight of my prod .js file?
Or any chance I can eject the config in order to add the --debug flag?

Typescript Support

Hello fellow developers!

Is there any Typescript support ? I tried to implement it myself but failed :(

I tried following this: https://webpack.js.org/guides/typescript/ but it didn't work and spew a bunch of errors out.

ERROR in ./app/shortcode.ts 11:75
Module parse failed: Unexpected token (11:75)
File was processed with these loaders:
 * ./node_modules/ts-loader/index.js
You may need an additional loader to handle the result of these loaders.
|     for (var i = 0; i < shortcode_containers.length; ++i) {
|         var objectId = shortcode_containers[i].getAttribute('data-object-id');
>         ReactDOM.render(wpObject, (_a = { window: window }, _a[objectId] = , _a) /  > , shortcode_containers[i]);
|     }
| });

Hope someone can help me :)

Cannot load css file from an external module.

I am trying to add React Tostify module on a clean install of your plugin as a shortcode and I have problems loading the css file from this module. I am loading the css file in shortcode.jsx via:

import 'react-toastify/dist/ReactToastify.css';

I get the following error:

Uncaught Error: Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.

.Toastify__toast-container

I've tried putting the css file in the same folder as the shortcode and play around with webpack.config.js but nothing seems to work. Any advice would be appreciated.

Accessing the WP Reactivate settings page throws error

Visiting this directory /wp-admin/options-general.php?page=wp-reactivate on my local Wordpress install throws this error in the console:

Admin.jsx:16 Uncaught TypeError: Cannot read property 'api_url' of undefined at
Admin._this.getSetting (Admin.jsx:16)

The error is referring to this function:

  getSetting = () => {
    fetch(`${this.props.wpObject.api_url}settings`, {
      credentials: 'same-origin',
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': this.props.wpObject.api_nonce,
      },
    })
    .then(response => response.json())
    .then(
      (json) => this.setState({ settings: json.wpreactivate }),
      (err) => console.log('error', err)
    );
  };

local changes not showing up in the web app

Changes to the admin panel are not showing up under settings. Even after I run the build command.
Expecting the following to show up on the admin panel:
```

WP Reactivate Settings

Demo Setting: ``` but nothing mounts.

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.