Another technical blog post for my own reference; this time to explain to myself how to use React Context when working on webapps which are based on WordPress’ implementation of React. I’ll keep this simple and assume that you know the basics of React and its implementation. (Most of this syntax is 1:1 from React, so it should work without using the @wordpress/element package too.)

The idea of using Context is that you don’t have to pass properties around between various components: instead, you define values at the top-level of the app and then make them available throughout the component structure.

First off, you’ll hang your app onto a DOM element. This is the simplest integration and the one which I have used dozens of times across many WordPress projects.

import { createRoot } from '@wordpress/element';

const element = document.querySelector('[data-mywebapp]'),
		root = createRoot(element);
root.render(<App element={element} />);

The functionality of the app is in the app.js script. I won’t bother going into a complex example, as the basics of Context are pretty extensible. I’m writing this post as a reminder of how to copy and paste in basic code. 😉

The Context is like a data store, into which and from which we can store and access variables. The context component is defined like this in the file context.js.

import { createContext } from '@wordpress/element';

export const AppContext = createContext();

Then we connect that to the main app.js and store the values we want to reuse.

import { AppContext } from './context';
import { ShowID } from './show-id';

export const App = ({element}) => {

    // Get the post ID from the data attribute on the DOM element
    const postId = {element.dataset};

    // Save the post ID to the app-wide context
    const context = {
        postId
    };

    // Wrap the app components in an AppContext Provider
    return (
        <AppContext.Provider value={context}>
            <ShowID />
        </AppContext.Provider>
    );
};

The ShowId component can now read (and write) the value of postId from the context object as follows.

import { useContext } from '@wordpress/element';
import { AppContext } from './context';

export const ShowId = () => {
    const context = useContext(AppContext);
    const { postId } = context;

    return <div>The post ID is {postId}.</div>
};

Leave a Reply

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

For security, use of Google’s reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

This site uses Akismet to reduce spam. Learn how your comment data is processed.