This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Gutenberg colour palette by className

I have run into an issue with the Gutenberg color palette because it always returns the HEX value of the selected color. What I wanted were options to select a color value in the admin, but have a css class string on the frontend with my selection.

Here is a simple React component that does just that. It selects and displays the colors in the admin the same way that native color palette does, but for the frontend, it outputs the provided string as an attribute.

Put this component inside your codebase, but make sure that you have all the imports provided using node_modules.

import { find } from 'lodash';
import { useState } from 'react';
import { getColorObjectByColorValue } from '@wordpress/editor';
import { ColorPalette } from '@wordpress/components';

export function ColorPaletteCustom({
  colors,
  value,
  onChange,
  disableCustomColors = true,
  clearable = false,
  label,
  help,
}) {
  const [color, setColor] = useState(value);

  const colorValue = find(colors, { name: color });

  return (
    <div className="components-base-control">
      {label && <label htmlFor="color-pallete" className="components-base-control__label">{label}</label>}
      <br />
      <ColorPalette
        colors={colors}
        disableCustomColors={disableCustomColors}
        value={typeof colorValue === 'undefined' ? color : colorValue.color}
        onChange={(newColor) => {
          const colorObject = getColorObjectByColorValue(colors, newColor);
          
          setColor(() => newColor);
          onChange(typeof colorObject === 'undefined' ? '' : colorObject.name);
        }}
        clearable={clearable}
      />
      {help && (
        <p className="components-base-control__help">{help}</p>
      )}
    </div>
  );
}

Next, go to your block and import this component inside the InspectorControls component.

 <ColorPaletteCustom
  label={'Color'}
  colors={[
    { name: 'red', color: '#D8262C' },
    { name: 'pink', color: '#F2BCC0' },
    { name: 'black', color: '#000000' },
  ]}
  value={styleColor}
  onChange={
    (event) => props.setAttributes({ styleColor: event })
  }
/>

This component supports all the props that you can use on the Gutenberg color palette the same way, so for detailed documentation, check this link.

Loading React in a WordPress Theme

Now that WordPress ships with React, it is important to know how to properly enqueue it your themes.

The overall process includes the following:

  1. List wp-element as a dependency for your own React code
  2. Setup a build tool (I recommend WP Scripts)
  3. Setup a custom page template where your React code will load
  4. Write your React code

You can check out the final source code here if you want to jump ahead.

Make React a Dependency

When you enqueue your own JavaScript you can simply include wp-element as a dependency and all of the functions from React and ReactDOM will be loaded on the page in a global window object named wp.element.

Here is some example code you could add to your functions.php file:

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
 
    wp_enqueue_script(
        'my-theme-frontend',
        get_stylesheet_directory_uri() . '/build/index.js',
        ['wp-element'],
        time(), //For production use wp_get_theme()->get('Version')        
        true
    );
  
}

This is all you need to do!

If your JavaScript file is located somewhere else you will want to change /build/index.js, however, this will work with the default settings for WP Scripts.

Setup Your Build Tool (WP Scripts)

WP Scripts is a command line toolkit from the WordPress team that will bundle your JavaScript code. It includes webpack as well as some other tools and makes them all work with very little configuration.

To start, create a package.json file in the root folder of your theme and add the following:

{
  "name": "theme-name",
  "version": "1.0.0",
  "description": "A demo theme with React",
  "main": "index.js",
  "devDependencies": {
    "@wordpress/scripts": "^5.1.0"
  },
  "scripts": {
    "build": "wp-scripts build",
    "check-engines": "wp-scripts check-engines",
    "check-licenses": "wp-scripts check-licenses",
    "lint:css": "wp-scripts lint-style",
    "lint:js": "wp-scripts lint-js",
    "lint:pkg-json": "wp-scripts lint-pkg-json",
    "start": "wp-scripts start",
    "test:e2e": "wp-scripts test-e2e",
    "test:unit": "wp-scripts test-unit-js"
  },
  "author": "Zac Gordon",
  "license": "ISC"
}

Then run npm install. This will get everything setup and installed for you.

Now, you can create your main JavaScript/React file at /src/index.js and WP Scripts will automatically bundle everything and save it to /build/index.js.

You can change the entry and output paths for the webpack configuration, but it is easiest to just use the defaults.

Create a Custom Page Template

For this demo we will create a simple custom page template inside a Twenty Twenty Child Theme that you can find the full code for here.

<?php
/**
 * Template Name: React Template
 */
get_header();
?>

<main id="site-content" role="main">
	<article class="post-2 page type-page status-publish hentry">
		<?php get_template_part( 'template-parts/entry-header' ); ?>
		<div class="post-inner thin">
			<div class="entry-content">				

				<div id="react-app"></div><!-- #react-app -->

			</div><!-- .entry-content -->
		</div><!-- .post-inner -->
	</article><!-- .post -->
</main><!-- #site-content -->

<?php get_template_part( 'template-parts/footer-menus-widgets' ); ?>
<?php get_footer(); ?>

The important thing is that we have a custom div with an id of react-app. This is where we will load our custom React code.

You could also have your React code added to a header, footer, widget area or pretty much anywhere on a WordPress site you need it.

Write Your React Code

Now we can create our /src/index.js file and add some React code.

Here is some basic code to create a <Vote /> component that let’s people click a button to increase the count of votes. It is not very practical and the data does not get saved or connected to WordPress, but it does demonstrate how to write React in your WordPress Theme.

const { render, useState } = wp.element;

const Votes = () => {
  const [votes, setVotes] = useState(0);
  const addVote = () => {
    setVotes(votes + 1);
  };
  return (
    <div>
      <h2>{votes} Votes</h2>
      <p>
        <button onClick={addVote}>Vote!</button>
      </p>
    </div>
  );
};
render(<Votes />, document.getElementById(`react-app`));

The code above will display a button that increases the votes on click. You can customize this as needed as well as begin creating and importing in other files and components as you would expect with a React app.

Happy Reacting!

React will become more commonplace in WordPress themes and plugins so hopefully this article helps you get more comfortable loading and using React in your projects.