Learning Redux
eBook - ePub

Learning Redux

Daniel Bugl

Compartir libro
  1. 374 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Learning Redux

Daniel Bugl

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Build consistent web apps with Redux by easily centralizing the state of your application.About This Book• Write applications that behave consistently, run in different environments (client, server and native), and are easy to test• Take your web apps to the next level by combining the power of Redux with other frameworks such as React and Angular• Uncover the best practices and hidden features of Redux to build applications that are powerful, consistent, and maintainableWho This Book Is ForThis book targets developers who are already fluent in JavaScript but want to extend their web development skills to develop and maintain bigger applications.What You Will Learn• Understand why and how Redux works• Implement the basic elements of Redux• Use Redux in combination with React/Angular to develop a web application• Debug a Redux application• Interface with external APIs with Redux• Implement user authentication with Redux• Write tests for all elements of a Redux application• Implement simple and more advanced routing with Redux• Learn about server-side rendering with Redux and React• Create higher-order reducers for Redux• Extend the Redux store via middlewareIn DetailThe book starts with a short introduction to the principles and the ecosystem of Redux, then moves on to show how to implement the basic elements of Redux and put them together. Afterward, you are going to learn how to integrate Redux with other frameworks, such as React and Angular.Along the way, you are going to develop a blog application. To practice developing growing applications with Redux, we are going to start from nothing and keep adding features to our application throughout the book. You are going to learn how to integrate and use Redux DevTools to debug applications, and access external APIs with Redux. You are also going to get acquainted with writing tests for all elements of a Redux application. Furthermore, we are going to cover important concepts in web development, such as routing, user authentication, and communication with a backend serverAfter explaining how to use Redux and how powerful its ecosystem can be, the book teaches you how to make your own abstractions on top of Redux, such as higher-order reducers and middleware.By the end of the book, you are going to be able to develop and maintain Redux applications with ease. In addition to learning about Redux, you are going be familiar with its ecosystem, and learn a lot about JavaScript itself, including best practices and patterns.Style and approachThis practical guide will teach you how to develop a complex, data-intensive application leveraging the capabilities of the Redux framework.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Learning Redux un PDF/ePUB en línea?
Sí, puedes acceder a Learning Redux de Daniel Bugl en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in JavaScript. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2017
ISBN
9781786469533
Edición
1

Combining Redux with React

Until now, we have only covered managing application state, which is what Redux focuses on. However, a web application also has a user interface, which Redux does not take care of. This is where React comes into play.
In this chapter, we are going to cover:
  • What React is and why it is useful
  • Setting up and using React
  • Creating React components
  • Connecting React components to Redux
Finally, we are going to create a small blog application with React and Redux, which will be further extended in the upcoming chapters.

Why React?

In the previous chapter, we manually rendered the user interface using Document Object Model (DOM) operations to generate HTML code with JavaScript. As you can imagine, it would be quite painful to have to manually do DOM operations to build your entire user interface. This is where React comes in. From React's official documentation: React - A JavaScript library for building user interfaces.
React takes a new approach to building user interfaces, by making use of functional programming principles—similarly to Redux!

The principles of React

Similarly to Redux, React also comes with a set of principles, as follows:
  • Declarative: This means you write code of what you want and do not have to think about how to do it.
  • Component-based: You can split your application into multiple modules and combine them to build complex user interfaces.
  • Learn once, write anywhere: React is a library, not a framework. It is independent of your stack and you can use it in the browser, on the server, or even on mobile apps (using React Native).
These principles might remind you a bit of Redux—the reason for that is Redux being heavily inspired by React, and both libraries are inspired by functional programming principles.

Setting up React

Before learning how to use Redux with React, we should first get familiar with React itself. We are going to use the project template (the first code example) from Chapter 2, Implementing the Elements of Redux.
Firstly, we have to install React and ReactDOM via npm:
npm install --save react react-dom
React is the core library, which deals with user interface components.
ReactDOM renders React components to the DOM, which, in this case, means that HTML will get rendered in the browser.
There are also other renderers for React, such as React Native. It allows you to render your application to native mobile apps, such as Android and iOS. You can find more information at https://facebook.github.io/react-native/.

Rendering simple text

Now, we can import both libraries and render simple text. Edit src/index.js and replace the contents with the following code:
  1. Start by importing React and ReactDOM:
import React from 'react' import ReactDOM from 'react-dom'
  1. Then, we use ReactDOM to render our application to the HTML DOM:
ReactDOM.render(
  1. The first argument is a React component to be rendered. In this case, we create a new React component from the h1 element, with the hello world! content:
React.createElement('h1', {}, 'hello world!'),
The function signature for React.createElement is as follows:
React.createElement(type, props, children)
The HTML equivalent for this would be:
<type ...props>children</type>
  1. The second argument of ReactDOM.render is the target. We select the div we defined in the index.html file, which has the ID root:
 document.getElementById('root')
)
  1. Save the file and start the webpack via:
npm start
  1. Then, visit http://localhost:8080/ in your browser to see the h1 element being rendered!
Our first React application

Rendering with JSX

You might be thinking that for more complex user interfaces, you will have to use React.createElement a lot, which would be messy. React provides a JavaScript extension called JSX, which allows you to describe React components with HTML-like syntax. Remember the h1 element we created earlier?
React.createElement('h1', {}, 'hello world!')
With JSX, it would look like this:
<h1>hello world!</h1>
JSX is an HTML-like syntax, but not exactly HTML. You have to be careful in some cases because the attributes are named after the DOM property names. For example, you cannot write:
<h1 class="title">hello world!</h1>
You have to use className instead because that is the name of the DOM property:
<h1 className="title">hello world!</h1>
Thankfully, most HTML attributes have the same name as their DOM properties. class is special because it is a reserved keyword in the JavaScript language.
The only other attribute that is renamed because of these conflicts is for, which got renamed to htmlFor.

Setting up JSX

To be able to use JSX, we need to install the React plugin for Babel. It will then compile JSX into proper calls to the React API. Firstly, we need to install the babel-preset-react package:
npm install --save-dev babel-preset-react
In addition to installing the preset, we also need to tell Babel to use it. Edit .babelrc, find the "presets" property, and add "react" to the array. It should look like this now:
{ "presets":[ "es2015", "react" ], "plugins": [ "transform-object-rest-spread" ] }

Using JSX

Now that we have JSX set up, let's use it! Edit src/index.js and replace the following line:
 React.createElement('h1', {}, 'hello world!')
With the JSX version:
 <h1>hello world!</h1>
The whole file should look like this now:
import React from 'react' import ReactDOM from 'react-dom' ReactDOM.render(  <h1>hello world!</h1>, document.getElementById('root') )
Restart the application and visit http://localhost:8080/; it should look the same way as before.

Example code

The example code can be found in the chapter3_1.zip attachment.
Unpack the zip, change into the directory, run npm install and npm start, and open http://localhost:8080 in your browser.

First steps with React

In the previous section, you learned how to create simple HTML elements with React, through React.createElement. Toward the end, you learned how to do the same thing with JSX.
In this section, you are going to learn more about creating simple as well as more advanced React components.

Creating a simple React element

Just like other JavaScript values, you can store React elements in a variable/constant:
const greeting = <h1>hello world!</h1>
If you have JSX code that spans across multiple lines, you can wrap it in ( and ) brackets, as follows:
const greeting = ( <h1> hello world! </h1> )
There is something else that makes JSX special—you can embed JavaScript expressions in JSX by wrapping them in curly brackets { }. That way, you can display ...

Índice