Before we get to the “How”, let’s talk a little bit about the “Why” of implementing React in Drupal. React, as you know, is a very developer-friendly, component-based JavaScript library that lets developers build high-quality, complex front-end interfaces. Drupal is a robust and powerful content management framework that enables content-driven and flexible web experiences. Combining React’s superior front-end theming capabilities with Drupal’s powerful back-end framework can let you deliver performant and exceptional digital experiences. Let’s take a closer look at creating React components in Drupal 9.

React Quickly in Drupal

But first, what is React?

By definition: “React is a declarative, efficient, and flexible JavaScript library for building frontend user interfaces. It lets you compose complex UIs from small and isolated pieces of code called components.”

If you are familiar with Pattern lab, it should be easy for you to understand React’s basic building blocks. We start with the basic building blocks or atoms of a page and work our way up to create designs.

Create Designs

A lot of developers prefer to use JSX to write HTML code in React. Read on to find out why.

Why JSX for React

React’s coding style and syntax can get complex and is not very developer-friendly. As you see below, this is how an HTML element is created in React.

const element = React.createElement (
{className: 'greeting'},
'Hello, world!'

And this is how you write the same function in React using JSX:

const element = <h1 className="greeting">Hello World!</h1>

Using JSX you can specify the name of the class as mentioned below using the predefined “className” XML syntax. As you can see, it is much easier, intuitive and less verbose to write the same code in JSX. Hence, almost the entire React community uses JSX to write React code.

What is JSX? JSX stands for JavaScript XML. XML is a very user-friendly syntax for developers. JSX makes it easier to write and add HTML in React.

Take a look at the difference between creating elements in React vs Javascript. You will notice how React gives you more flexibility to write and access code, making it easy to develop and debug.

React Javascript

const Button = <button onClick={console.log('clicked!')}>Click Me</button>


<button id="my-button">Click Me</button>


function onClick() {
const button = document.getElementById('my-button');
button.addEventListener('click', onClick);



Although JSX makes it easy for developers to write code, it is not the best format for browsers to understand. For this reason, we will be compiling it into a regular JavaScript format that will be served to the browser.

React Data Forms

React components have two forms of data:

    • Props
        ◦ Props are properties received from ancestors in the component hierarchy. They cannot be changed, or mutated. For example, to pass a variable from a parent to a child component, you can pass it as a prop.
    • State
        ◦ State is local to a component, and can be changed by events. For example, if you have a state variable (state.text), the text can be changed according to different actions. 

NOTE: Child components can receive both the values of that state and events to update that state through props

How to Integrate React with Drupal

We’ll first start by creating a custom module and then the JSX file.
Now let’s create the Drupal custom module as shown below: 
Create modules/react/

web > modules > react > !
1 name: React
2 type: module
3 description: 'A module for basic React components.'
4 core_version_requirement: *8.7.7 || ^9

Next, let’s create the React file as shown below. We’re creating an HTML markup with an H1 tag that will be printed in the react-app id. 

Create modules/react/js/src/index.jsx

web > modules > react > js > src > # index.jsx
1 import React from 'react';
2 import ReactDOM from 'react-dom';
4 ReactDOM. render(
5  <h1>Hello there - world!</h1>,
6  document. getElementById( ' react—app')
7  );

Accessing the JSX file by Drupal

Now, for Drupal to be able to access and use the JSX file that we just created, you will need to set up a JavaScript toolchain with Webpack.

At a high level, we're configuring a process that'll take our source JavaScript files, like index.jsx, and pass them through different build steps that will ultimately output a single, optimized, .js file. This build step allows us to take advantage of the entire React/JavaScript ecosystem while working on our Drupal module or theme.

The basic steps are:

  • Set up a toolchain that'll process your JavaScript assets into one or more "bundled" JavaScript files with a known location that doesn't change
  • Create a Drupal asset library that points to the bundled assets from your build toolchain

Step 1: Install React, Webpack, and Babel

Before installing these, you will need to ensure you have node and nmp ready in your development environment. React is the Javascript library. Babel and webpack are compilers you need to convert the .jsx to javascript for the browser. Babel is one of the best community compilers to compile .jsx files. To install React, Webpack and Babel, run the following commands from the root directory of your theme modules/react/, in your terminal

1 # Create a package.json if you don't have one already.
2 npm init -y
3 # Install the required dependencies
4 npm install —-save react react-dom prop—types
5 npm install —-save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader webpack webpack-cli

Step 2: Configure Webpack with a webpack.config.js file

Create a webpack.config.js file in the root of your module: modules/react/webpack.config.js

1 const path = require('path');
3 const config = {
4  entry: {
5    main: ["./js/src/index.jsx"]
6  },
7  devtool:'source-map',
8  mode:'development',
9  output: {
10    path: path.resolve(__dirname, "js/dist"),
11    filename: '[name].min.js'
12  },
13  resolve: {
14    extensions: ['.js', '.jsx'],
15  },
16  module: {
17    rules: [
18      {
19        test: /\.jsx?$/,
20        loader: 'babel-loader',
21        exclude: /node_modules/,
22        include: path.join(__dirname, 'js/src'),
23      }
24    ],
25  },
26 };
28 module.exports = config;

Step 3: Configure Babel with a .babelrc file

Provide some configuration for Babel by creating a .babelrc file with the following readily available presets (which will be used while compiling the React code) in the root directory of the module: modules/react/.babelrc

web > modules > react > .babelrc >...
1 {
2  "presets": [
3    "@babel/preset-env",
4    "@babel/preset-react"
5  ]
6 }

Step 4: Add some helper scripts to package.json

This is necessary to run your nmp package as it always refers to the base file package.json before any action.

 > Debug

 "scripts": {
   "build": "webpack",
   "build:dev": "webpack",
   "start": “webpack —-watch"

Step 5: Run build to compile the jsx files to the single js file

Now we are ready to compile the JSX file.

  npm run build  (OR) npm run build:dev

Basically this compiles the file as per the config in the webpack.config file and now it creates the compiled js file to the mentioned repository js/src/dist.

Step 6: Define a Drupal asset library

You can now add the compiled JavaScript file as a Drupal asset in the library (libraries.yml).

web > modules > react > ! react.libraries.yml

1 react_app:
2  version: 1.0
3  js:
4    js/dist/main.min.js: {minified: true}

Now you are all set and ready to create some cool React components in your Drupal website.

Here’s how my end result looked like (below). You can see the React block I created with an H1 tag “Hello Specbee”.


Final Thoughts

Wasn’t that easy? When creating React components in Drupal, make sure you have the React dom element created in Drupal (‘react-app’) and always attach the Javascript file (that we compiled from the React JSX file) to the Drupal library. Liked what you just read? We strive to publish valuable content for you every week. Subscribe to our weekly newsletter to stay updated with all our latest insights.

Santhosh KumarOct 11, 2022