React JS ❤️ Javascript

A review of some of the main Javascript features that React JS uses regularly

The && operator to paint elements conditionally

The && and || they work in a special way in Javascript because they behave like short circuits. This means that its result is not always a Boolean as in other languages, but what we will obtain will be one of the elements that is operating.

  • If the first operand evaluates to false the second operator is not evaluated.
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>  );}

The map function to paint lists of items

Another Javascript function that is used repeatedly is the Array.prototype.map method that allows us to iterate over a list of elements and apply an individual operation to each one of them.

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>  );}

The arrow functions

If you have noticed, in the previous example to the map method we are passing a function expressed as “arrow function”. This shorter syntax is very useful when we use it within JSX, since it allows us to express the iteration over the elements in a much shorter way (in addition to not using an extra pair of keys, the code is more readable):

const products = ['iPhone', 'iPad', 'Apple Watch'];function Products() {  return (    <ul>      {products.map(function(product) { 
return (<li key={`product--${product}`}>{product}</li>);
})}
</ul> );}
// Sin arrow function
class 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 function
class AwesomeComponent extends React.Component{
onClick = (event) => {
// ...
}
render(){
return (
<button type="button"
onClick={this.onClick}>
Click
</button>
);
}
}

Object Destructuring

Another feature that Javascript offers us and that we repeatedly work with in React is the destructuring of objects, which allows us to assign their properties directly to variables:

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

ES Modules

Another feature that Javascript provides us with are the modules, thanks to the import-export syntax that allows us to “bring” functionality declared in other files to use within ours.

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

🧙🏼‍♂️ Trick

Remember that if you want to work with absolute imports in your application, you just have to create a jsconfig.json file in the root of the project with the following content:

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

Backticks

Another feature that ES6 incorporated at the time and that is very useful when working with React is the backtick.

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

One of the most recent incorporations that we have received in Javascript is the “chaining operator” which allows us to access the properties of the objects safely, without worrying about whether along the way we will find an undefined that causes a failure:

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 and fetch

Finally, in a compilation of Javascript utilities that are used in React, neither the promises nor of course the fetch function to make calls to external APIs could be missing:

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>
);
}

Final thoughts

As you have seen with all the examples I have mentioned, React in the end is just a library located on top of Javascript to help us develop our applications much faster but at all times we are resorting to the characteristics of the language to implement our functionality.

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