Getting started with React and Drupal

Getting started with React and Drupal

Over the weekend I decided it was long overdue that I learnt React, or at least understood what all the fuss was about, so with npm in hand I installed yarn and started my quest.

We're going to use Create React App to setup our base React install. First install then run the command to create a react app called "drupal-react":
npm install -g create-react-app
create-react-app drupal-react
cd drupal-react

You can now run npm start (or yarn start) to start your app locally and open it in a browser. Here you'll see a React default page, this is all created from a React component called "App". If you take a look at the file src/App.js you will see the component and how the render() method returns the page HTML as JSX. We need to replace to the code returned here to show some Drupal nodes, so how about replacing it with (or just adding) <NodeContainer />. This will call a new component, so at the top of app.js we will also need to import that, so with the other import code add import NodeContainer from './NodeContainer';.

Now to create the NodeContainer component. First we need to add the Axios library which we'll use to query the Drupal REST API, run npm install axios --save. Then create the file src/NodeContainer.js, and in there add the following code:
import React, { Component } from 'react'
import axios from 'axios'

class NodeContainer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      nodes: []
    }
  }

  componentDidMount() {
    axios.get('http://example.com/api/nodes')
    .then(response => {
      this.setState({nodes: response.data})
    })
    .catch(error => console.log(error))
  }

  render() {
    return (
      <ul>
       {this.state.nodes.map((node) => {
          return(
           <li={node.nid}>{node.title}</li>
          )
        })}
      </ul>
    )
  }

}

export default NodeContainer

At the top of the file React and Axios are both imported, the class for NodeContainer is then created. The constructor method is where we add the state node, componentDidMount() is called to get the nodes from the View /api/nodes, which then gets rendered as an unordered list.

To create the /api/nodes view install the core Rest module. This will allow you to create a "REST Export" view. Here the path can be set to /api/nodes, and you can select nid, and title.

As long as you left npm start running, you should be able to go back to your browser, and view a nice list of Drupal nodes being rendered in React.

Next, routing, to make these node titles clickable! 😱

timmillwood Mon, 23/04/2018 - 07:20

Comment

Submitted by ygerasimov (not verified) on Tue, 24/04/2018 - 02:05

Permalink

Hey Tim,

Thank you for putting this together.

Any recommendations about material to learn plain React? Preferably with PHP as backend. Like laracasts for vuejs.

Yuriy

Add new comment