Categories
WordPress + React

Render Application with WordPress React

You don’t need to install React if you work with the WordPress environment. Like many other frameworks, WordPress release their own React-based package which helps us to use the same function and methods. In this case, @wordpress/element will be an alternative way.

Install a package

If you have a theme or plugin repository with package.json:

npm install --save @wordpress/element

If you don’t have a package.json and just want to build a minimal script with pure ECMA5 script:

add_action('wp_enqueue_scripts', get_stylesheet_directory_uri() .  '/assets/main.js', array('wp-element'), '1.0.0', true);

I will suggest you start with NodeJS more than using a second way.

Render an application

I guess you have a file src/index.js which will be used for compiling assets.

import { render } from '@wordpress/element'
import Header from './components/Header'
import Main from './components/Main'
import Footer from './components/Footer

const App = () => {
  return (
    <div className={'ct-app'}>
      <Header />
      <Main />
      <Footer />
    </div>
  )
}

window.addEventListener('DOMContentLoaded', () => {
  render(<App />, document.getElementById('ct-app-root'))
}

Notes

  • render() is a React method but now we use with package @wordpress/element. Read a document to see more other functions you could use.
  • A root app in React should be a single div. In case you wish to output multiple divs, it’s requires to insert <Fragment> outside those elements.

Leave a Reply

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