Specbee: How to React Quickly in Drupal

How to React Quickly in Drupal Santhosh Kumar 11 Oct, 2022 Subscribe to our Newsletter Now Subscribe Leave this field blank

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.

Image removed.

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.

Image removed.

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 ( 'h1', {className: 'greeting'}, 'Hello, world!' );

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

const element = Hello World!

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 = Click Me

HTML FILE

Click Me

JS FILE

function onClick() {
 console.log('clicked!');
};
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/react.info.yml

web > modules > react > ! react.info.yml 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'; 3 4 ReactDOM. render( 5 Hello there - world!, 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'); 2 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 }; 27 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”.

Image removed.

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.

Author: Santhosh Kumar

Meet Santhosh Kumar, an Acquia certified Drupal 9 Frontend specialist. While he’s not turning complex problems into simple interface designs, you can find him either binge-watching Jackie chan movies or dancing. His best-kept secret (well, not anymore)? He sleeps with his eyes open! Image removed.

Drupal Drupal 9 Drupal 9 Module Drupal Development Drupal Planet

Leave us a Comment

 

Recent Blogs

Image Image removed.

How to React Quickly in Drupal

Image Image removed.

Configuring the Drupal 9 Metatag Module - A Brief Guide

Image Image removed.

What Search Engines want and why Drupal is better for SEO

Want to extract the maximum out of Drupal? TALK TO US

Featured Success Stories

Image removed.

Upgrading and consolidating multiple web properties to offer a coherent digital experience for Physicians Insurance

Image removed.

Upgrading the web presence of IEEE Information Theory Society, the most trusted voice for advanced technology

Image removed.

Great Southern Homes, one of the fastest growing home builders in the United States, sees greater results with Drupal 9

View all Case Studies

Community Working Group posts: Code of Conduct team update: September 7 - October 5, 2022

The Community Health Team’s Code of Conduct committee met on September 7 and 21 and October 5 as part of its ongoing efforts to develop and update the Code of Conduct (CoC) for the Drupal community. You can read previous updates on the Community Working Group’s blog.

Members present at the September 7 meeting were:

At the September 7 meeting, the team reviewed and incorporated comments made by community stakeholders to the "Revised Code of Conduct Elements" Google Doc. This document consisted of various elements and example text based on the team's review of various other community codes of conduct. In this round, the team incorporated additional feedback solicited from community members based outside of North America and Europe.

Some of the feedback included:

  • Use plain, easy-to-understand English (no contractions, idioms, etc.)
  • Add a need to understand local cultural sensitivities before getting into conflict resolution
  • Include references to Drupal’s Values and Principles
  • Make it clear that those who are in high visibility and/or leadership positions have additional responsibility, as the project and community may be judged by their actions

Donna Bungard volunteered to edit the updated document into an initial Code of Conduct draft that would then be further edited by George DeMet for the team to review at the September 21 meeting.

Members present at the September 21 meeting were:

At the September 21 meeting the team reviewed the initial draft Code of Conduct and made additional edits based on internal feedback. Much of the draft language was edited to make it easier to read and understand, using online tools such as the Hemingway Editor and Readable.

The team agreed to share the draft document with the full Community Health Team as well as other community stakeholders for feedback. This feedback will be reviewed at the team’s next meeting, with further rounds of revision and review being made as needed prior to sharing with the community-at-large.

Members present at the October 5 meeting were:

During the October 5 meeting, the team reviewed and rationalized the feedback and suggestions that had been made by the full Community Health team and other community stakeholders. The team agreed to continue to work asynchronously to make additional updates and solicit feedback as needed.

If you, or a Drupal-related group, is interested in being part of this process as a community stakeholder, please let us know at drupal-cwg at drupal dot org.

Talking Drupal: Talking Drupal #368 - Image Optimization

Today we are talking about Image Optimization with Martin Anderson-Clutz.

For show notes and more visit:

www.talkingDrupal.com/368

Topics
  • Image optimization
  • Why it is important
  • Performance
  • Accessibility and Inclusion
  • Techniques with Drupal
  • Image formats
    • webp
    • svg
    • avif
  • Drupal support
  • What to do before uploading
  • Educating content editors
  • Difference in formats
  • Helpful modules and tools
    • Core
      • Image Styles
      • Responsive Images
    • Contrib
      • Blazy for older sites
      • Crop API, and Focal Point or Image Widget Crop
      • WebP or similar
      • SVG Image Field
      • Image Optimize API, and Local Binaries Resmush.it or similar
    • Image Library
      • Imagemagick
      • GD Library
  • Anything else
Resources Guests

Martin Anderson-Clutz - @mandclu

Hosts

Nic Laflin - www.nLighteneddevelopment.com @nicxvan John Picozzi - www.epam.com @johnpicozzi Tearyne Almendariz - @tearyneg

MOTW

Toolbar Manager Allow a site builder to customize what items appear in the toolbar:

  • Change text labels
  • Add classes (e.g. to add icons)
  • Or hide entirely

DrupalEasy: Drupal Talent Scholarships. Because if we’re not growing, we’re stagnant

Image removed.One of the challenges of growing and keeping an open source community vibrant is attracting individuals and helping them to understand the opportunities the technology offers, how they can master it, and how they can get a job. Those who may want to point their careers toward Drupal often don’t know how to get started, where to find a path, nor have the resources to do it. It can be a daunting undertaking that has likely caused more than a few people to move on to traditional careers with paths that are more clear and accessible. 

We started Drupal Career Online, our career technical education certificate program, as the first of its kind for Drupal over 10 years ago at the behest of the workforce board on Florida’s Space Coast seeking new career and training opportunities for those whose jobs fell victim to the end of America’s Space Shuttle program. We created it on the model of countless other career technical education programs that feed a variety of industries with an ongoing flow of new talent, with the added element of community; which has helped us to create a truly unique and valuable learning experience. We built the program, secured our licensure with the Florida Department of Education, and it has developed into the premier Drupal career-training program worldwide. 

We’ve been working for more than a decade to build it and to help bolster the Drupal talent pipeline through the DCO as well as working with other training organizations to really make an impact on how we can help get people into the Drupal talent pipeline. We’ve partnered (and tried to partner) with regional workforce boards, colleges, non-profits and Drupal organizations in a variety of ways (and through more than a couple of attempts) to help bring more people into Drupal. 

After all of this effort and time, we’re really excited about the extraordinary response and results we’ve gotten as we have ramped up DrupalEasy scholarship programs. Organizations who are supporting the Discover Drupal career training program and those who are stepping up to sponsor their own, dedicated scholarships to Drupal Career Online are making amazing strides in attracting talent, especially individuals from underrepresented groups, to the community through their tuition sponsorship, mentorships and entry-level employment opportunities.  

As our scholarship program evolves, we are formalizing things to make sure there is a clear path for more organizations that want to get in on improving the flow of talent into the Drupal talent pipeline. We are making sure we can keep building on the spirit of the program as we scale up the number of members who would like to be a part of the effort with Discover Drupal through the Drupal Association, or directly sponsor their very own scholarship for Drupal Career Online. 

We’d love to seem more companies and organizations join the Drupal Association’s thoughtful Discover Drupal sponsors, or become direct DCO sponsors like Palantir.net, Four Kitchens and Bounteous as they cooperatively recruit to attract diverse people from outside of the community to learn more about Drupal as a career, offer scholarships to the DCO, provide mentoring and provide graduates with paths to becoming Drupal professionals.  

Please contact us if you’d like to discuss how sponsoring a student scholarship for Drupal Career Online might help you recruit some fresh talent and bring more, and more diverse people into the Drupal Community. 




 

#! code: DrupalCon Prague 2022

Last week I visited the city of Prague to attend the European DrupalCon 2022. The even was held between September 20th and 23rd, and was attended by over 1,200 people.

This was my first physical conference since DrupalCamp London 2020, and the first DrupalCon I have attended since DrupalCon Dublin 2016. Despite the worries about covid I was still pretty exited to attend the event. I arrived on Monday night and as the event didn't start properly until Tuesday afternoon it gave me a small chance to explore the city of Prague before the conference started.

There were so many talks, sessions, meetings, and events during DrupalCon that I could write for pages and pages about the conference. I am quite sure, however, that no one would actually read all of that I'll just post a couple of highlights from each day and provide a sum up at the end.

Image removed.

Tuesday

After the initial welcoming talk the conference started with an introduction to some of the initiatives that are being worked on at the moment, each one introduced by a member of the initiative team. The initiatives discussed where CKEditor 5, project browser, project update bot, GitLab integration, localize.drupal.org, distributions and recipes, and automatic updates.

Read more.