React JS ❤️ Javascript

Un repaso a algunas de las principales características de Javascript que React JS usa habitualmente

El operador && para pintar elementos de forma condicional

console.log("Cat" && "Dog"); // 'Dog'
console.log(false && "Dog"); // false
function Bar() {  const condition = false;  return (    <div>      {/* Este elemento no se renderizará */}      {condition && <Foo />}    </div>  );}

La función map para pintar listas de elementos

const arr = [1, 2, 3];const doubled = arr.map(n => n * 2); // [2, 4, 6]
const products = ['iPhone', 'iPad', 'Apple Watch'];function Products() {  return (    <ul>      {products.map(product => <li key={`product--${product}`}>   {product}</li>)}   </ul>  );}

Las arrow functions

const products = ['iPhone', 'iPad', 'Apple Watch'];function Products() {  return (    <ul>       {products.map(function(product) { 
return (<li key={`product--${product}`}>{product}</li>);
})}
</ul>);}
// Sin arrow functionclass AwesomeComponent extends React.Component{
constructor( props ){
super( props );
this.onClick = this.onClick.bind(this);
}
onClick(event){
// ...
}
render(){
return (
<button type="button"
onClick={this.onClick}>
Click
</button>
);
}
}
// Con arrow functionclass AwesomeComponent extends React.Component{ onClick = (event) => {
// ...
}
render(){
return (
<button type="button"
onClick={this.onClick}>
Click
</button>
);
}
}

Desestructuración de objetos

const person = {id: 1, name: 'Gerardo'};const {id, name, telephone = 'default telephone'} = person;console.log(id); // 1console.log(telephone); // 'default telephone'
function Button({onClick, text}) {
...
}
const lunch = ['🍝', '🥩', '🍎', '☕'];const [firstCourse] = lunch;console.log(firstCourse); // '🍝'
const [count, setCount] = useState(0);

Módulos de ES

import React, {useState} from 'react';
const FooComponent = React.lazy(() => import('./foo'))
import {Suspense} from 'react';function Bar() {
return (
<Suspense fallback="Cargando...">
<FooComponent />
</Suspense>
);
}

🧙🏼‍♂️ Truco

{  "compilerOptions": {    "baseUrl": "src"  }}
import {HOME_PATH} from '../../../config/router/paths';
import {HOME_PATH} from 'config/router/paths'

Las comillas invertidas

const name = 'Gerardo';
const surname = 'Fernández';
const telephone = '123 123 123';
// "Old syntax"const userInfo = 'User info: ' + name + ' ' + surname + ' ' + telephone;// "New syntax"const userInfo = `User info: ${name} ${surname} ${telephone}`;
function CounterView({counter}) {
return (<div>{`Valor del contador: ${counter}`}</div>);
}

Chaining operator

const person = {
name: 'Gerardo',
email: 'mail@mail.com'
}
console.log(person.currentJob.title);// Uncaught TypeError: Cannot read property 'title' of undefined
const jobTitle = person?.currentJob?.title; // undefined

Promesas y fetch

import React, {useEffect, useState} from 'react';function MyComponent() {  const [users, setUsers] = useState(null);  useEffect(async function() {    const response = await fetch('https://reqres.in/api/users');    const json = await response.json();    setUsers(json.data);  });  if (!users) {    return <div>Todavía no hay usuarios</div>;  }  return (    <ul>     {users.map(user => <li key={`user--${user.id}`}>{user.first_name}</li>)}   </ul>  );}

Conclusiones

¿Quieres recibir más artículos como este?

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store