Using React library on Drupal Without JSX simple example

  0 comments

There are two way to integrate React with drupal

  • Headless Drupal app
  • React app embedded in Drupal

Headless Drupal app

 

If you implement headless Drupal, you then build a separate React application which will communicates with the backend via API requests, just as you would use with any backend system. React then does not really care what is in the backed. It only needs to be able to use the exposed API.

 

React app embedded in Drupal

 

you will add React library to your website, just like you would add any other js library (e.g. a jQuery or some other library for a slider or gallery).

 

There is a lot of good documentation here to include library :

1. https://www.drupal.org/docs/8/api/javascript-api/add-javascript-to-your-theme-or-module
and 

2. https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

To make it easy you can include the following scripts in your html.html.twig in your template:

   
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    

 

Then you need to place HTML tag in your markup in which the React app will live. It can be a div rendered in a block or by a custom controller on a separate route.

 


<div id="reactapp"> </div>

 

And create JavaScript file name with reactapp.js which will contains your APP. It must be include in footer. Since, it will not work if you will include before above HTML tag.

 

ReactDOM.render(
  React.createElement(HelloComponent, {toWhat: 'World'}, null),
  document.getElementById('myreactapp')
);

 

Now you need to define your component which you did declare above "HelloComponent"

 

class Hello extends React.Component {
  render() {
    return React.createElement('div', null, `Hello ${this.props.toWhat}`);
  }
}

 

Currently we are using simple text in react component.

 

In next blog I will post how to use API in react component.

Add new comment