Integrate Drupal 8 with React Material-UI

December 26, 2019

Tags: Drupal, APIs,

As we know Drupal has many cool features. One of them is JSON: API. Through JSON: API we can get a list of API resources. 

The purpose of this blog is to show how we can integrate Drupal 8 with React Materialize in three simple steps.

Before creating an API, it is vital to discuss the Drupal backend process.

For this, you'll need the JSON:API module. JSON: API is now part of Drupal core. So we only need to enable it. For more details please refer: JSON: API 

Next navigate to admin > content. Click on add content and create articles.

Blog109_1

Image source: Photo by Virginia State Parks via Flickr and Pixabay

Step 1 - Create a Drupal API

  • After enabling the JSON: API module you will get some default resources 

  • In this blog we are using two resources article ( /jsonapi/node/article) and file (/jsonapi/file/file)

Step 2 - Use the Materialize component in React

  • The first step is to create the React app 

Check https://create-react-app.dev/docs/getting-started/ 

  • The second step is to install Material-UI and Axios in the React app. Check Material-UI document - https://material-ui.com and https://www.npmjs.com/package/axios 

  • The third step is to import the Material-UI component in the React files. At here, I am creating two React files App.js and Image.js 

  • App.js -  for fetching details of the article and render into HTML

  • Image.js - for fetching article related media 

Step 3 - Next, call Drupal API from React.

  • At here, I am calling API from the localhost. componentDidMount() is a React lifecycle method which is called after all the elements of the page are rendered correctly.

App.js

Blog109_2

Image.js

Blog109_3

Now you can successfully call Drupal API from React.     

Next, let's discuss UI creation.

In this blog, we are creating React Materialize Card using Drupal API. For creating card we need card related components and icons.

Blog109_4

Let's import these Material-UI components in React files.

App.js

Blog109_5

Image.js

Blog109_6

Next use these components inside render function of React files.

App.js

Blog109_7

Image.js

Blog109_8

The cool thing is we have seen how we can call Drupal API from React like any other API and use Material-UI components. With the help of Material-UI, we can include styles without writing CSS in a specific file.

Note: If you use the absolute URL of the localhost then you will get CORS related console error. Make sure that you use a relative URL if you are calling API from the localhost. 

One way to resolve CORS error is by adding proxy in package.json.

package.json is used to add dependency packages and versions to your projects. For more details, you can refer - https://docs.npmjs.com/creating-a-package-json-file 

Blog109_9

I hope this was helpful and interesting! You can view the complete code here: https://github.com/Sumit55/Drupal-and-Materialize-React

Good luck!