How to use React.js as Frontend and Drupal8 as backend ?

  0 comments Share with:

In previous blog I had covered on How to use react with Drupal in which we had placed simple text in react APP.

 

In this blog I shall cover on how to use a REST API in Drupal with React APP using React Library.

 

First we need to include following JavaScript files from React.js library. So, that we can use react Class and its functions :-
 

<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>


If we use only these two above mentioned JavaScript files then we cannot use JSX or Typescript. So, in this blog we shall also cover how to use JSX

Introducing JSX


Consider this variable declaration:
 

const element = <h1>Hello, world!</h1>;


It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.


I will not go along with all details about JSX as is not the purpose of this blog, and you can find them on the official website.
 

so, now we will need to add another JavaScript library using which we will able to use JSX
 

Add below JavaScript library in your project.
 

    
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>

 

The first thing to you have to create is an 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="myreactapp" />


Now it's the time to write JSX which will define react class and component which will call rest API and place content in React App.
 


So, you need to add JavaScript tag and don’t forgot to add type as “text/jsx”
 


it will look like that
 

<script type="text/jsx">
///Write code here
</script>


Create your app
 

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


Create your component
 

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://example.org/api")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="row">
          {items.map(item => (
                <a href={item.field_url_link}>
                <div className="listing col-12 col-md-6 col-lg-4 col-xl-6 mb-3">
                  <div>
                    <img src={item.field_upload_screenshot_image} alt={item.title} />
                  </div>
                  <p>{item.title}</p>
               </div>
		</a>
          ))}
        </div>
      );
    }
  }
}


We are calling an API which will give list for portfolio page and we are integrating that result in JSX variable which will integrate with React JS and output in react APP.
 


You can make Rest API in drupal 8 using a view rest export. I will not go along with all details about this. You can find them on the official website.
 


View the full code below :-
 

<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>

<script type="text/jsx">
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://example.org/api")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="row">
          {items.map(item => (
                <a href={item.field_url_link}>
                <div className="listing col-12 col-md-6 col-lg-4 col-xl-6 mb-3">
                  <div>
                    <img src={item.field_upload_screenshot_image} alt={item.title} />
                  </div>
                  <p>{item.title}</p>
               </div>
		</a>
          ))}
        </div>
      );
    }
  }
}
ReactDOM.render(
  React.createElement(MyComponent, {toWhat: 'World'}, null),
  document.getElementById('myreactapp')
);
</script>


you can use above example to replace any area according to your needs at any page you can replace left side bar, right sidebar as well as main content etc. For that you have to create different component.
 

Add new comment