Learning ReasonReact Step by Step Part: 0

09/12/20191 Min Read — In Reason, React.js

My goal is to learn more in public, so that it also may help others.

I've given ReasonReact a first try. I've read a bit of the documentation, took a peek into Exploring ReasonML, and found some useful blog posts.

Let's try to build a form in Reason React!

This is a simple project, but forms are one of the most common things you'll need in a web application.

Installation & Setup

Installation via npm or yarn is painless:

$ yarn add -g bs-platform

Create a new project:

$ bsb init reason-form -theme react-hooks

This command bootstraps a new ReasonReact project called "reason-form" with React hooks.
Go to the directory and install the necessary modules:

$ cd reason-form && yarn install

Clean Up Webpack etc.

The default configuration for running the project with npm or yarn is cumbersome. You have to run two scripts in two separate terminals.

I use concurrently to run several scripts in parallel.

$ yarn add --dev concurrently

Modify package.json. Delete the scripts and replace with the following:

"scripts": {
"start": "concurrently -k \"yarn run start:bsb\" \"yarn run start:webpack\"",
"start:bsb": "bsb -clean-world -make-world -w",
"start:webpack": "webpack-dev-server --port 3000",
"build": "concurrently -k \"yarn run build:webpack\"",
"build:webpack": "NODE_ENV=production webpack",
"format": "refmt src/*.re"

Create The First Component

Remove the example components in the src folder.

Delete the content of src/index.html and replace with the following:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<title>Reason Form</title>
<div id="root"></div>
<script src="Index.js"></script>

This adds Bulma and a div with id "root" where we will mount our Reason React app.

The HTML loads JavaScript from Index.js - that's how it's configured with webpack. Take a look at webpack.config.js if you want to know more.

Modify scr/Index.re:

ReactDOMRe.renderToElementWithId(<App />, "root");

Create the src/App.re file:

let make = () =>
<div className="App"> {"Hello World" |> ReasonReact.string} </div>;

The strange looking syntax is ReasonReact's way of writing JSX.

The decorator and the make function create a React component. Inside the div you have to tell Reason that you're dealing with a string.

It sure doesn't look pretty.

Run ReasonReact

Go to the terminal:

$ yarn run start

Go to http://localhost:3000 and you should see "Hello World".

Further Reading