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<br>create-react-app drupal-react<br>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></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'<br>import axios from 'axios'<br><br>class NodeContainer extends Component {<br> constructor(props) {<br> super(props)<br> this.state = {<br> nodes: []<br> }<br> }<br><br> componentDidMount() {<br> axios.get('http://example.com/api/nodes')<br> .then(response => {<br> this.setState({nodes: response.data})<br> })<br> .catch(error => console.log(error))<br> }<br><br> render() {<br> return (<br> <ul><br> {this.state.nodes.map((node) => {<br> return(<br> <li>{node.title}</li><br> )<br> })}<br> </ul><br> )<br> }<br><br>}<br><br>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
Tags
drupal planet
drupal-planet
drupal
drupal8
drupal 8
drupal development
react
reactjs
javascript
Add new comment