ReasonML Quick Start Guide
eBook - ePub

ReasonML Quick Start Guide

Build fast and type-safe React applications that leverage the JavaScript and OCaml ecosystems

Raphael Rafatpanah, Bruno Joseph D'mello

Share book
  1. 180 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

ReasonML Quick Start Guide

Build fast and type-safe React applications that leverage the JavaScript and OCaml ecosystems

Raphael Rafatpanah, Bruno Joseph D'mello

Book details
Book preview
Table of contents
Citations

About This Book

A hands on approach to learning ReasonML from the perspective of a web developer.

Key Features

  • Hands on learning by building a real world app shell that includes client-side routing and more.
  • Understand Reason's ecosystem including BuckleScript and various npm workflows.
  • Learn how Reason differs from TypeScript and Flow, and how to use it to make refactoring less stressful.

Book Description

ReasonML, also known as Reason, is a new syntax and toolchain for OCaml that was created by Facebook and is meant to be approachable for web developers. Although OCaml has several resources, most of them are from the perspective of systems development. This book, alternatively, explores Reason from the perspective of web development.

You'll learn how to use Reason to build safer, simpler React applications and why you would want to do so. Reason supports immutability by default, which works quite well in the context of React.

In learning Reason, you will also learn about its ecosystem – BuckleScript, JavaScript interoperability, and various npm workflows. We learn by building a real-world app shell, including a client-side router with page transitions, that we can customize for any Reason project. You'll learn how to leverage OCaml's excellent type system to enforce guarantees about business logic, as well as preventing runtime type errors.You'll also see how the type system can help offload concerns that we once had to keep in our heads.

We'll explore using CSS-in-Reason, how to use external JSON in Reason, and how to unit-test critical business logic. By the end of the book, you'll understand why Reason is exploding in popularity and will have a solid foundation on which to continue your journey with Reason.

What you will learn

  • Learn why Reason is exploding in popularity and why it's the future of React
  • Become familiar with Reason's syntax and semantics
  • Learn about Reason's ecosystem: BuckleScript and JavaScript interoperability
  • Learn how to build React applications with Reason
  • Learn how to use Reason's type system as a tool to provide amazing guarantees
  • Gain a solid foundation on which to continue your journey

Who this book is for

The target audience of this book is web developers who are somewhat familiar with ReactJS and who want to learn why ReasonML is the future of ReactJS.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is ReasonML Quick Start Guide an online PDF/ePUB?
Yes, you can access ReasonML Quick Start Guide by Raphael Rafatpanah, Bruno Joseph D'mello in PDF and/or ePUB format, as well as other popular books in Computer Science & Web Programming. We have over one million books available in our catalogue for you to explore.

Information

Year
2019
ISBN
9781789344233
Edition
1

Creating ReasonReact Components

Now that we've set up our development environment, we're ready to get started with ReasonReact—the future of ReactJS. Both ReasonML and ReasonReact were built by the same person who built ReactJS. ReasonReact is just Reason, much like how ReactJS is just JavaScript. Throughout the rest of this book, we will be working with an application that we will start building in this chapter. The following are screenshots of what we'll have built by the end of this chapter:
To follow along, clone this book's GitHub repository and start from Chapter03/start. Throughout the rest of this book, each directory shares the same development environment as the one we set up at the end of Chapter 2, Setting Up a Development Environment.
git clone https://github.com/PacktPublishing/ReasonML-Quick-Start-Guide.git
cd ReasonML-Quick-Start-Guide
cd Chapter03/start
npm install
We'll first explore ReasonReact, and at about halfway through this chapter, we'll shift to the Chapter03/app-start directory, where we'll start building an application with ReasonReact's built-in router.
In this chapter, we will do the following:
  • Explore creating stateless and stateful ReasonReact components
  • Create an application that includes navigation and routing
  • See how so many of the ReactJS concepts you're already familiar with map nicely to ReasonReact
  • Learn how ReasonReact can help us create more robust components thanks to Reason's type system

Component creation basics

Let's start by analyzing a simple stateless component. In App.re, let's render a <div /> element with some text:
let component = ReasonReact.statelessComponent("App");

let make = _children => {
...component,
render: _self => <div> {ReasonReact.string("hello world")} </div>,
};
And in Index.re, render the component to a DOM element with an ID of "root":
ReactDOMRe.renderToElementWithId(<App />, "root");
Due to Reason's module system, we do not need an import statement in Index.re nor an export statement in App.re. Every Reason file is a module, and every Reason module is globally available. Later in this book, we will see how a module's implementation details can be hidden so that users of your component only access things they are supposed to access.

Component templates

In ReasonReact, all components are created with one of the following four functions:
  • ReasonReact.statelessComponent
  • ReasonReact.statelessComponentWithRetainedProps
  • ReasonReact.reducerComponent
  • ReasonReact.reducerComponentWithRetainedProps
Each of the four functions accepts a string and returns a record corresponding to a different component template. The string argument is only for debugging purposes. The component gets its name (<App />) from its filename (App.re). The fields the returned record contains are dependent on which of the functions was used. In the case of our previous example, we have the following fields that we can override:
  • render
  • didMount
  • willReceiveProps
  • shouldUpdate
  • willUpdate
  • didUpdate
  • willUnmount
Aside from the render field, the rest are just familiar ReactJS life cycle events. To override a field, add that field within the make function's returned record. In the preceding example, the component template's render field was replaced with the custom render function.
The make function accepts props as arguments, and returns a record of the same shape as the one that was initially created by one of the four component creation functions. The last argument to the make function must be the children prop. You may have noticed that children is prefixed with an _ in the preceding example. If your component does not need a reference to the children prop, then prefixing the argument with an _ prevents a compiler warning for the unused binding.
It may not appear immediately obvious, but the make function's curly braces belong to the returned record literal. The ...component expression spreads the contents of the original record in this new record so that individual fields can be overridden without having to explicitly set each field.

self

The render field holds a callback function that accepts an argument called self, and returns a value of type ReasonReact.reactElement. The three fields of the self record are the following:
  • state
  • handle
  • send
By choice, ReasonReact does not have the concept of JavaScript's this. Instead, self holds the necessary information and is provided to callbacks that need it. We'll see more of self when using stateful components.

Event handlers

In our render function, we can attach event listeners to DOM elements the same way that we would in ReactJS. For example, to listen for the click event, we add an onClick attribute and set its value to an event handler:
let component = ReasonReact.statelessComponent("App");

let make = _children => {
...component,
render: _self =>
<div onClick={_event => Js.log("clicked")}>
{ReasonReact.string("hello world")}
</div>,
};
However, this callback function must accept exactly one argument (corresponding to a JavaScript DOM event) and must return a type called unit.

unit

In Reason, unit is a type that means "nothing." A function whose return type is unit cannot return anything other than unit. There is exactly one value of type unit: () (that is, a pair of empty parentheses, which is also called unit).
In contrast, there are exactly two values of type bool: true and false. There are an infinite number of values of type int.
As discussed in Chapter 1, Introduction to ReasonML, the idiomatic way to represent a nullable value in Reason is with the option type. The major difference between the option type and the unit type is that a value of type option could be nothing, or it could be some value where as a value of type unit is always ().
A function that accepts and/or returns unit likely causes side effects. For example, Js.log is a function that returns unit. The onClick event handler is also a function that returns unit.
Random.bool is an example of a function that accepts unit as its argument and returns a bool. The syntax for calling a function with unit is quite familiar:
Random.bool()
Since onClick needs a function that returns unit, the following will result in a type error:
let component = ReasonReact.statelessComponent("App");

let make = _children => {
...component,
render: _self =>
<div onClick={_event => 42}> {ReasonReact.string("hello world")} </div>,
};
The type error is shown here:
Error: This expression has type int but an expression was expected of type
unit
In the error message, This expression refers to 42.

JSX

Reason comes with the JSX syntax. One difference in ReasonReact's version of JSX is that we cannot do the following in ReasonReact:
<div>"hello ...

Table of contents