This tutorial will introduce OCaml, Reason React, and BuckleScript, and explain their relevance. To wrap things up, we will take a look at a demo project built with ReasonReact. ReasonReact is a simpler and much safer way to build React components in Reason, and with the help of BuckleScript, we can have access to a JavaScript version of all code written in Reason. More about this later in the tutorial.

Introduction

The importance of productivity in programming is very crucial to the success of any Software Engineer in particular, as it facilitates an implementation of features on time, working successfully with a very large team, and my favorite, being able to sleep at night without getting worried about the new code you just merged with the master branch.

There are many competing programming paradigms, each with their own approaches to application flow, syntax and other conventions.

Easy access to relevant tools, you will agree with me, will go a long way to not only make you productive as a Software Engineer but also enhance your current skill set.

The semantics

OCaml is an expressive and dynamic strictly typed general purpose programming language. It lays more emphasis on expressiveness and safety. Its been around for a while (over 20 years) now but its popularity has been on the lower side due to its small community. Most notable companies make use of it to minimize errors and improve speed. Facebook, for example, uses OCaml to developed type checkers like Hack for PHP and Flow for JavaScript.

The syntax

Reason on the other hand is not another programming language per say, but a new syntax and toolchain powered by OCaml. It provides a familiar, usable interface intended to make interoperation with JavaScript and adoption by JavaScript developers easier. In view of this, ReactReason was introduced to give JavaScript developers, especially the ReactJS community, to leverage the greater type system of Reason.

The compiler

BuckleScript compiles OCaml/Reason code down to plain JavaScript that can easily be shipped to virtually any browser in the world. One of the benefits of BuckleScript is the amazing speed at which it compiles down to human-readable JavaScript.

Getting started

Run the command below to globally install BuckleScript on your machine:

 $ npm install -g bs-platform 

Once the installation process is completed, we will now fully have access to the bsbcommand that would be used to easily initialize a quick Reason project.

Creating a basic project

By now, you should have BuckleScript installed successfully. To see it in action, let’s generate a lightweight Reason project template with:

 $ bsb -init reason-sample-project -theme basic-reason 

The boilerplate should have a similar project structure as shown here:

Next, run a command to build the project from the terminal in the root directory of the project:

 $ npm run build 

Did you notice a new file Demo.bs.js that was quickly generated for the project? The compiled version of Reason to JavaScript is housed by this file. Feel free to check and view it.

Lastly, type node src/demo.bs.js in your terminal to run the JavaScript output.

This will log a message Hello, BuckleScript and Reason! to the console. Now open the project with your favorite text editor and make a change to the message within the Js.log()method located in ./src/Demo.re , then proceed to build and see your changes.

Concepts overview

Reason introduces a new way of writing OCaml and still retains access to the beauty of static types. Let’s take a quick look at some basic concepts of Reason, such as variants, functions, and pattern-matching since we’ll be using it to build a demo.

Variants in Reason are data types and structures. It can be used to define sets of symbols and data structures. You can read more about variant here.

 /* ./src/Demo.re */ type animal = Cat(string) | Dog(string); 

We have the type of an animal which can either be a Cat or Dog and both will only accept a string as an argument.

Functions in Reason are declared with an arrow and a return expression. Declare one as shown here:

 /* ./src/Demo.re */ let speak = (animal) => switch (animal) { | Cat(name) => name ++ " says: meow" | Dog(name) => name ++ " says: woof" }; 

Here, what we have done is to declare a function speak and passed an argument using the type that was declared earlier. Within it, we used a switch expression and checked for every possible case of the animal variant, this is referred to as pattern-matching in Reason. One of the advantages of pattern-matching is that it is very exhaustive, you will get a warning in the console if you did not check for both cases.

Furthermore, for each of the variants, we passed a variable name and later concatenated it with a statement representing what we want each of the animal to say.

Now we can simply call the function and passed any of the types of animal into it:

 /* ./src/Demo.re */ Js.log(speak(Dog("Cooper"))); Js.log(speak(Cat("Buddy"))); 

Navigate to ./src/Demo.bs.js to see the equivalent JavaScript version of the functions declared in Reason above as compiled by BuckleScript.

Let’s build a todo app with Reason

To get a better grasp of the concept of building web applications with Reason, we’ll use Reason-scripts to build a simple todo list application. This will be a familiar experience for ReactJS users that are conversant with create-react-app. While building this app we will get a much better introduction to the syntax and type system of Reason.

Prerequisites

A basic understanding of React will be of great assistance with this tutorial. Before we get started, we need to install some required set of tools:

  1. We will be using create-react-app to create a boilerplate for this project. Run this command from your terminal to install it globally on your machine:
 $ npm i -g create-react-app 
  1. Finally head over to editor setup to get the Reason plugin for your favorite editor as this will help facilitate the development process.

Creating the Reason React project

We’ll create our project using the create-react-app command. Navigate to your project folder and run a command that will create a project named reason-bucklescript-todo:

 $ create-react-app reason-bucklescript-todo --scripts-version reason-scripts 

Next, change directory into the newly created project and first, run npm link bs-platformand start the application with npm start or yarn start:

ReasonReact components

Similar to a ReactJS application, ReasonReact supports the use of components to structure an application. By default, the create-react-app already generated a basic App component for us. Navigate to ./src/App.re and edit as follow:

 /* ./src/App.re */ [%bs.raw {|require('./App.css')|}]; [@bs.module] external logo : string = "./logo.svg"; let component = ReasonReact.statelessComponent("App"); let make = (~message, _children) => { ...component, render: _self => <div className="App"> <div className="App-header"> <img src=logo className="App-logo" alt="logo" /> <h2> {ReasonReact.string(message)} </h2> </div> <div className="App-intro"> <Todo /> </div> </div>, }; 

Since the structure of the file above is similar to what we would have for other components, let’s take a quick look at some of its parts.

First, we required a stylesheet with [%bs.raw {|require('./App.css')|}]; at the top of the file. BuckleScript allows us to include some raw JavaScript code by using [%bs.raw ] and wrapping the JavaScript code with {| |}.

Defining a component

Next, a component can either be stateless or stateful. In ReasonReact, there are different ways of defining them:

  1. Stateless components: defined as ReasonReact.statelessComponent("componentName")
  2. Stateful components: defined as ReasonReact.reducerComponent("componentName")

Furthermore, we declared a make function which takes in two different parameters. The first parameter has a symbol ~ indicating that it was passed into the App component as a propsand the second parameter has _, this is a more explicit way of showing that the parameter isn’t used and ignored.

In addition, the …component spread operator indicated that the make function declared is building upon the component that was just defined. We also declare a render function with a single argument _self that is not used at the moment.

Rendering a string in ReasonReact is a little bit different than what we have in ReactJS, here you will have to wrap the string with a function named ReasonReact.string().

Finally, we included and rendered a component <Todo /> without importing any file, interesting right? In ReasonReact, every component is a module and doesn’t need to be imported before it can be used in another module. We’ll create this Todo component in a bit.

Creating components

For a better folder structure, we will group all new components in the same directory that will be named components. For BuckleScript to detect the Reason files and compile them easily to JavaScript we’ll need to edit the BuckleScript configuration file. Open ./bsconfig.json and add a new source as shown below:

    // ./bsconfig.json
{
  "name": "reason-scripts",
  "sources": [
    "src",
    "src/components" // Add this line
  ],
  ...
}

With the configuration above, any .re file created within the components directory will be compiled down to JavaScript. Before we start creating the required files, locate the srcdirectory and create another directory named components inside of it.

Set up the todo component

First, let’s create a new file, TodoType.re in the components directory and paste the code below in it. This will define the data structure for the list of Todo items:

 /* ./src/components/TodoType.re / type item = { id: int, title: string, completed: bool, };

As pointed out earlier, every file in ReasonReact is a module and all the things defined at the top level of the file using the keywords let, type, and module are exposed to be used from other files. So in other components we will need to reference the TodoType component that we just created.

Todo component

Navigate to the src/components directory and create a new file Todo.re within it. Open the new file and paste in this code:

 / ./src/components/Todo.re / type state = { items: list(TodoType.item), inputText: string, }; type action = | InputText(string) | Toggle(int) | RemoveItem(int) | Submit; let component = ReasonReact.reducerComponent(“Todo”); let make = children => { let handleSubmit = state => { let newId: int = List.length(state.items); let newItem: TodoType.item = { id: newId, title: state.inputText, completed: false, }; let newList = [newItem, …state.items]; ReasonReact.Update({items: newList, inputText: “”}); }; { …component, initialState: () => { items: [{id: 0, title: “Fix more bugs”, completed: false}], inputText: “”, }, reducer: action => switch (action) { | InputText(newText) => ( state => ReasonReact.Update({…state, inputText: newText}) ) | Toggle(id) => (state => ReasonReact.Update({ …state, items: List.map((item: TodoType.item) => item.id == id ? { …item, TodoType.completed: ! TodoType.(item.completed), } : item, state.items, ), }) ) | RemoveItem(id) => ( state => ReasonReact.Update({ …state, items: List.filter( (item: TodoType.item) => item.id !== id, state.items, ), }) ) | Submit => (state => handleSubmit(state)) }, render: self => { let {items, inputText} = self.state; <div className=“app”> <div className=“app-header”> <div className=“title”> {ReasonReact.string(“Todo List”)} </div> </div> <Input submit=( => self.send(Submit)) value=inputText onInputText=(text => self.send(InputText(text))) /> <div className=“list”> ( ReasonReact.array( Array.of_list( List.map( (item: TodoType.item) => <Item key=(string_of_int(item.id)) item onRemove=(id => self.send(RemoveItem(id))) onToggle=(id => self.send(Toggle(id))) />, items, ), ), ) ) </div> </div>; }, }; };

The file above is an example of a stateful component in ReasonReact. And within it, first, we defined the state for the component and a set of actions that will be required to mutate the state of each item. And within the make function of the component, we defined a function named handleSubmit to handle the addition of new item and then update the existing todo list once created.

Next, we defined the initialState of the todo items and added a reducer method which takes the action as a parameter and used pattern-matching on the action type, returning a ReasonReact.Update which contains the new state.

Input component

This component will be used to add an item to a to-do list and therefore can be maintained as a stateless component since its main function is to emit an event that will trigger the handleSubmit function within the Todo component. Create this file within ./src/componentsand name it Input.re. Once you are done, paste the content below in it:

 / ./src/components/Input.re / let component = ReasonReact.statelessComponent(“Input”); let make = (~value, ~onInputText, ~submit, _children) => { …component, render: self => <div className=“input”> <input value placeholder=“Enter item and click add” onChange=( event => onInputText( ReactDOMRe.domElementToObj(ReactEventRe.Form.target(event))##value, ) ) /> <button onClick=( => submit())> (ReasonReact.string(“Add”)) </button> </div>, };

Item component

Finally, we will define a stateless component for rendering the items as they are being added. To do this, create a new file named Item.re within ./src/components directory and paste the code below:

 / ./src/components/Item.re / let component = ReasonReact.statelessComponent(“Item”); let make = (~item: TodoType.item, ~onRemove, ~onToggle, _children) => { …component, render: self => <div className=“item”> <input type=“checkbox” checked=item.completed onChange=( => onToggle(item.id)) /> <p> {ReasonReact.string(item.title)} </p> <button onClick=( => onRemove(item.id))> {ReasonReact.string(“Remove”)} </button> </div>, };

Stylesheet

Open ./src/App.css and paste the code below to add some styling to the application:

    / ./src/App.css */

  .App {
    text-align: center;
  }
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
    height: 80px;
  }
  .App-intro {
    font-size: large;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
  .App-header {
    background-color: #222;
    height: 150px;
    padding: 20px;
    color: white;
  }
  .app {
    width: 500px;
    margin: 10px;
  }
  .app-header {
    margin: 10px;
  }
  .title {
    font-size: 25px;
    font-weight: 500;
  }
  .input {
    display: flex;
    justify-content: flex-start;
  }
  .input input {
    width: 80%;
    height: 30px;
    padding: 5px;
    font-size: medium;
  }
  .input button {
    background-color: green;
    color: white;
    font-size: medium;
    width: 30%;
    margin-left: 20px;
  }
  .list {
    margin-top: 25px;
  }
  .item {
    display: flex;
    border: #f5f5f5 2px solid;
    align-items: center;
    height: 30px;
    padding: 10px;
    margin-top: 5px;
    font-size: larger;
  }
  .item p {
    text-align: left;
    margin: auto;
  }
  .item button {
    padding: 10px;
    background-color: grey;
    font-size: 14px;
    opacity: 0.95;
  }
  @keyframes App-logo-spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

And that is it. You should have a functional todo app by now

Conclusion

I hope this very simple application was helpful enough to increase your enthusiasm for exploring Reason and its syntax.

We barely scratched the surface of some awesome features in Reason and BuckleScript. You can visit the documentation to learn more about it.

The source code for the todo app can be found here on GitHub.

#reactjs #javascript

7 Likes13.95 GEEK