Introduction

What is React?

React is a JavaScript library for building user interfaces.

Advantages

Declarative: React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

Declarative views make your code more predictable and easier to debug.

Component-Based: Build encapsulated components that manage their own state, then compose them to make complex UIs.

Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM.

Learn Once, Write Anywhere: We don’t make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code.

React can also render on the server using Node and power mobile apps using React Native.

What you should already know

This guide assumes you have the following basic background:

  • A general understanding of the Internet and the World Wide Web (WWW).
  • Good working knowledge of HyperText Markup Language (HTML) and Cascading Style sheet (CSS).
  • Some programming experience. If you are new to programming, try one of the tutorials linked on the main page about JavaScript.
  • Experience with JavaScript. Kwon the bases of the lenguaje and Object Oriented Programming.
Hello World

A Simple Component

React components implement a render() method that takes input data and returns what to display. This example uses an XML-like syntax called JSX. Input data that is passed into the component can be accessed by render() via this.props.

 class HelloMessage extends React.Component {
  render() {
   return (
    <div>
     Hello {this.props.name}
    </div>
   );
  }
 }
 ReactDOM.render(
  <HelloMessage name="Taylor" />,
   document.getElementById('hello-example')
  );
JSX

Consider this variable declaration

 const element = <h1>Hello, world!</h1>;

This funny tag syntax is neither a string nor HTML.
It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

Why JSX?

React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. We will come back to components in a further section, but if you’re not yet comfortable putting markup in JS, this talk might convince you otherwise.

Rendering Elements

Let’s say there is a <div> somewhere in your HTML file:

<div id="root"></div>

We call this a “root” DOM node because everything inside it will be managed by React DOM.
Applications built with just React usually have a single root DOM node. If you are integrating React into an existing app, you may have as many isolated root DOM nodes as you like.
To render a React element into a root DOM node, pass both to ReactDOM.render():

 const element = <h1>Hello, world </h1>;
 ReactDOM.render(element, document.getElementById('root'));
Components and Props

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

Function and Class Components

The simplest way to define a component is to write a JavaScript function:

 function Welcome(props) {
  return <h1>Hello, {props.name} </h1>;
 }

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.
You can also use an ES6 class to define a component:

 class Welcome extends React.Component {
  render() {
   return <h1>Hello, {this.props.name} </h1>;
  }
 }

The above two components are equivalent from React’s point of view.

State and Lifecycle

This is the local state of the component class:

 class Clock extends React.Component {
  constructor(props) {
  super(props);
   this.state = {date: new Date()};
 }
 render() {
  return (
   <div>
    <h1>Hello, world!</h1>
    <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
   </div>
   );
  }
 }

 ReactDOM.render(
  <Clock />, document.getElementById('root')
 );

This is the same code but adding Lifecycle methods:

 class Clock extends React.Component {
  constructor(props) {
  super(props);
   this.state = {date: new Date()};
 }
 render() {
  return (
   <div>
    <h1>Hello, world!</h1>
    <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
   </div>
   );
  }
 }

 componentDidMount() {
  this.timerID = setInterval(
   () => this.tick(),
   1000
  );
 }

 componentWillUnmount() {
  clearInterval(this.timerID);
 }

 tick() {
  this.setState({
   date: new Date()
  });
 }

 ReactDOM.render(
  <Clock />, document.getElementById('root')
 );
Handling Events

Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string.

Html

 <button onclick="activateLasers()">
  Activate Lasers
 </button>

React

 <button onClick={activateLasers}>
  Activate Lasers
 </button>
Conditional Rendering

In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.

 function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
   return <UserGreeting />;
  }
  return <GuestGreeting />;
 }
 ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />, document.getElementById('root')
 );
Lists and Keys

With react you can build collections of elements and include them in JSX using curly braces {}.

 function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
   <li key={number.toString()}>
    {number}
   </li>
  );
  return (
  <ul>{listItems}</ul>
  );
 }

 const numbers = [1, 2, 3, 4, 5];
 ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
 );

Forms

HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state. For example, this form in plain HTML accepts a single name:

 <form>
  <label>
   Name:
   <input type="text" name="name" />
  </label>
  <input type="submit" value="Submit" />
 </form>
Lifting State Up

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let’s see how this works in action.

 class Calculator extends React.Component {
   constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
   }

   handleCelsiusChange(temperature) {
   this.setState({scale: 'c', temperature});
  }

   handleFahrenheitChange(temperature) {
   this.setState({scale: 'f', temperature});
  }

  render() {
   const scale = this.state.scale;
   const temperature = this.state.temperature;
   const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
   const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

   return (
    <div>
      <TemperatureInput
      scale="c"
      temperature={celsius}
      onTemperatureChange={this.handleCelsiusChange} />
      <TemperatureInput
      scale="f"
      temperature={fahrenheit}
      onTemperatureChange={this.handleFahrenheitChange} />
      <BoilingVerdict
      celsius={parseFloat(celsius)} />
    </div>
   );
  }
 }
Composition vs Inheritance

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.

Thinking in React

React is, in our opinion, the premier way to build big, fast Web apps with JavaScript. It has scaled very well for us at Facebook and Instagram.
Start With A Mock:

  • Step 1: Break The UI Into A Component Hierarchy
  • Step 2: Build A Static Version in React
  • Identify The Minimal (but complete) Representation Of UI State
  • Step 4: Identify Where Your State Should Live
  • Step 5: Add Inverse Data Flow