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

Partager le livre
  1. 180 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et 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

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que ReasonML Quick Start Guide est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  ReasonML Quick Start Guide par Raphael Rafatpanah, Bruno Joseph D'mello en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Web Programming. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2019
ISBN
9781789344233
Édition
1
Sous-sujet
Web Programming

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 des matiĂšres