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

Buch teilen
  1. 180 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
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

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist ReasonML Quick Start Guide als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu ReasonML Quick Start Guide von Raphael Rafatpanah, Bruno Joseph D'mello im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Computer Science & Web Programming. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
2019
ISBN
9781789344233

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 ...

Inhaltsverzeichnis