Creating React Web App with Grails backend

By , last updated July 17, 2019

In this tutorial we will show how to create a website with client in React JS and Grails as a backend server.

For the purpose if this tutorial we will use IntelliJ IDEA as a development environment on MAC.

Create Grails project with React profile

The easiest way to start making React apps with Grails is to create a Grails project with a react profile. Refer to the official grails website for latest installation instructions.

We will create an empty client-server app by running the following command in a command line:

$ grails create-app reactGrailsApp --profile=react

Make sure that latest Grails and Java JDK are installed on your system. If you are unsure, check the versions by running a grails -v command:

| Grails Version: 3.3.9
| JVM Version: 1.8.0_171

Import the new project into Intellij IDEA

1. Open Intellij and select File -> New -> Project from existing Sources

2. Choose your new project in the dialog

3. Choose Import from external model

4. Let all the default settings be in the next step.

There may be some errors that will appear just after importing the project. They are often easy to solve by following the steps proposed by the IDEA.

In our case the error “Gradle DSL method not found: ‘runtimeOnly()'” is caused by the old gradle distributionUrl reference.

Set the reference to version 4.1:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-bin.zip

Start client and server

Our project structure includes both client in React and a server in Grails. It is a very handy setting as you will from now on start both the server and the client with one click.

In IDEA:
1. choose Server -> “bootRun” task from the gradle pane view to start the server.

2. choose client -> start task to start the web clinet.

In command line run:
1. ./gradlew server:bootRun
2. ./gradlew client:start

The application will mount at port 3000 per default.

Something is already running on port 3000 error

You may sometimes encounter an error that the port is already in use:

Something is already running on port 3000.

To fix it on MAC go to your Terminal window, run a search for processes running on port 3000 and kill it:

netstat -vanp tcp | grep 3000
kill -9

The result should be a “Welcome to Grails” screen with a default ApplicationController:

Start coding in React JS

The main file for a React Web app is a JavaScript file placed in the “client” folder and is called App.js.

Open App.js inside the “client” folder and make some changes:

All changes should be instantly seen in your browser upon saving the file:

Now you may continue making frontend features writing React JS code in the folder “client“.

Backend code goes into the folder “server” and needs to be written in Grails.