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

Condividi libro
  1. 180 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e 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

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
ReasonML Quick Start Guide è disponibile online in formato PDF/ePub?
Sì, puoi accedere a ReasonML Quick Start Guide di Raphael Rafatpanah, Bruno Joseph D'mello in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Web Programming. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2019
ISBN
9781789344233
Edizione
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 ...

Indice dei contenuti