Using ES6 Spread Operator in React

Using ES6 Spread Operator in React

If you are a React beginner, you may have came across the three dots syntax (...) in many React code examples which may have confused you. In fact, this syntax is part of ES6 and not React itself and it's used by two operators - the Spread and Rest operators.

The Spread operator lets you expand an iterable like a string, object or array into its elements while the Rest operator does the inverse by reducing a set of elemnts into one array.

Both operators have many use cases and are used nowadays by most JavaScript developers to achieve the old JS tricks without getting things complex. The dots syntax is supported in all modern browsers which means you can use it with React with no worries. In fact, since most React developers make use of build systems and transpilers such as Babel to support latest JS features, you can safely use the dots syntax in your React code.

Passing React Props Using the Spread Operator in JSX

You can use the ES6 Spread operator to pass props to a React component. Let's take an example for a component that expects two props:

function App() {
  return <Hello firstName="Ahmed" lastName="Bouchefra" />;
}

Using the Spread operator, you would write the following code instead:

function App() {
  const props = {firstName: 'Ahmed', lastName: 'Bouchefra'};
  return <Hello {...props} />;
}

According to the React docs:

You can spread the props attributes to pass it in JSX using the Spread operator which passes the whole props object. So when your intent is to pass the whole props object, that's fine to use!

This is a clean syntax but in some cases it may be considered an anti-pattern which means you need to avoid using it. But Why?

When you use the ...props syntax, you actaully expand the props object from the parent component, which means all its attributes are passed down the child component that may not need them all. This will make things like debugging harder.

Also according to the docs:

Spread attributes can be useful but they also make it easy to pass unnecessary props to components that don’t care about them or to pass invalid HTML attributes to the DOM. We recommend using this syntax sparingly.

Using the Spread Operator with setState() for Setting the Nested State

Let's suppose, you need to use the setState() method to update your component state. Since the setState() may work asynchronously in manu cases for performance reasons. You would need to write the following code:

this.setState((state) => ({
  state1: state.state1 + 1,
}))

The state1 variable which is part of our component state will be incremented by one.

Now, let's suppose we have a state with a nested object in our component:

this.state = {
  stateObj: {
    attr1: '',
    attr2: '',
  },
}

The Rest Operator in React Example

The dots syntax can be also used to call the Rest operator in ES6. It's mostly useful when you want to avoid using the arguments object to access the passed arguments to a function.

This is an example pattern that uses the Rest operator to create authenticated routes in React using React Router:

const AuthenticatedRoute = ({ ...rest }) => {
  const id = this.state;
  if (!id) {
    return <Redirect to= />;
  }
  return <Route {...rest} />;
};
// In Use
<AuthenticatedRoute
  path='/dashboard'
  data={this.state.data}
  render={() => (
    <SomeComponent someProps={this.someProps} />
  )}
/>

Conclusion

As a recap, we've seen various way to use the ES6 Spread operator in react such as for:

Passing props to child components,
Using the Spread operator with the setState() method for setting the nested data
Using the Rest operator in React.

Learn More

Thanks for reading!

ES6 Modules - Import, Export & Default for React Native Devs

ES6 Modules - Import, Export & Default for React Native Devs

ES6 Modules - Import, Export & Default for React Native Devs

Originally published at techiediaries.com on 08 Aug 2019

I have been exploring React Native for building mobile apps with React and JavaScript. After generating my first project and started looking at the code, I noticed the use of the ES6 modern features like the import and export statements for importing and exporting modules and arrow functions, etc.

In this article, we'll focus on understanding the importexport and default keywords.

In the App.js file, we have the following code, truncated for the sake of brevity:

import React, {Fragment} from 'react';
/* [...] */

const App = () => {
return (
<Fragment>
<!-- [...] -->
</Fragment>
);
};

/* [...] */

export default App;

In this file, we first import the React and Fragment APIs from the react package, next, we define a function-based React component that renders a bunch of React Native components. Finally, we export the App component using the export default statement.

The export and default keywords

The export keyword is used to export the symbol but what about the default keyword?

Simply put, when you export a symbol as default, you don't need to specify its name (pay attention here, this is the name used inside the module for the symbol) when you need to import it.

Now, if we look at the index.js file, we'll see the following code:

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

This is where our exported App component is imported using the import keyword:

import App from './App';

We can use any name instead of App and will be still importing the App component. Because it's exported by default. For example, we can write the following instead:

import MyApp from './App';

MyApp will be an alias for the App symbol (which is exported by default so we don't need to specify its "internal" name to import it).

I hope, you understand the meaning of default because it may be confusing since developers usually use the same name used inside the module to import from another JS file. In our example, we used the App name for importing the App component from the App.js file.

If you want to learn more about ES6 modules, continue reading below.

ES6 Modules

ES6 has introduced builtin support for modules in JavaScript so we don't need to use the other systems used in ES5 like:

  • CommonJS modules used in Node.js (CommonJS modules use module.exports for export code and require(path) to import code),
  • Asynchronous Module Definition (AMD) used in RequireJS.

For more information, read Writing Modular JavaScript With AMD, CommonJS & ES Harmonyand Axel Rauschmayer’s ExploringJS: Modules.

Now, what's a module?

A module is a piece of code that encapsulates the code for specific functionality. It makes it easy to write decoupled and easy maintainable and testable code.

You can create a JavaScript module by simply creating a JavaScript file with the js extension and use the export keyword for exporting a piece of code (a symbol) such as a function, object or variable. .

Note: Unlike CommonJS modules which are loaded synchronously, ES6 Modules are loaded asynchronously which is better suited for the frontend code.

In ES6, you can export a symbol in two ways:

  • Using named exports,
  • Default exports.

You can use both of them inside the same module but it's not recommended.

Default Export

Just like we've seen earlier, you can make a default export by using the export and default keywords in front of the symbol. Since it's the default export, you don't necessarily need to import it using the same name in your other JavaScript files but it is a common case to import default exports with the same names which were used to define them inside their modules.

Named Export

You can use named exports in a module for exporting multiple symbols by simply using the exportkeyword in front of each symbol. These exports can be distinguished from each other using their names and are called named exports.

We can change our App.js file as follows:

import React, {Fragment} from 'react';
/* [...] */

export const App = () => {
return (
<Fragment>
<!-- [...] -->
</Fragment>
);
};

/* [...] /

We simply remove the default keyword to make a named export instead of a default export.

We can then import the App component in the index.js file as follows:

import { App } from  './App';

First, we used the curly braces (ES6 destructuring assignment) and second we need to specify the same name used in the containing module i.e App.

If you have more than one named export. For example, AppHeader and Footer, you can write the following statement to import them:

import { App, Header, Footer } from  './App';

If you have a default export (for example the App function) and named exports (for example the Headerand Footer components), you can import them as follows:

import App, { Header, Footer } from  './App';

You can also import all the exported symbols using  and as:

import * as app from './App';

You can then access each named export as a property:

console.log(app.App);
console.log(app.Header);
console.log(app.Footer);
Conclusion

As a wrap-up, we've seen how to use the importexport and default keywords for working with ES6 modules in React Native.

Originally published at techiediaries.com on 08 Aug 2019

=======================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ The Complete React Native and Redux Course

☞ React Native - The Practical Guide

☞ React Native: Advanced Concepts

☞ Understanding TypeScript

☞ Typescript Masterclass & FREE E-Book

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ The Complete React Developer Course (w/ Hooks and Redux)

☞ React JS Web Development - The Essentials Bootcamp

☞ React JS, Angular & Vue JS - Quickstart & Comparison

☞ The Complete React Js & Redux Course - Build Modern Web Apps

☞ React JS and Redux Bootcamp - Master React Web Development

JavaScript ES6 Classes

JavaScript ES6 Classes

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

Classes are a fundamental part of object oriented programming (OOP). They define “blueprints” for real-world object modeling and organize code into logical, reusable parts. Classes share many similarities with regular objects. They have their own constructor functions, properties, and methods. In this tutorial, we’ll demonstrate how to create and work with ES6 classes.

Creating a class

You can create a class using the class keyword:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }

}



let person = new Person("Sam", 30)



person.name

//returns 'Sam'



person.age

//returns 30

Notice how we define our Person class with a constructor() function taking two arguments name and age. Using the this keyword, we set the name and age properties based on the provided arguments. Remember that the constructor function is called whenever we create a new instance of the Person class.

Similar to objects, we can read class properties using dot notation so that person.name returns Sam.

Defining properties and methods

You can define properties and methods for a class the same way you do for regular objects:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



let person = new Person('Tim', 40)



person.sayName()

//logs 'My name is Tim'



person.location = 'London'



person.location

//returns 'London'

Notice how we define a sayName() function within our Person class definition. Once we create a new instance of Person, we can call the method via person.sayName().

You can also add properties and methods on the fly. You’ll notice that while the location property isn’t defined in our constructor function, we can still dynamically add it later on for the person instance. Remember that if we created a new instance of Person, it would not have a location property because that property is not defined in the class definition. Only properties and methods that we explicitly define will be shared by all instances of the class.

Static functions

You can use the static keyword to make class methods static. A static method acts on the class itself, not on instances of the class:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



Person.describe()

//logs 'This is a person.'

Notice how static methods operate on the class itself and not an instance of the class. We didn’t have to create a new Person to call the static method.

Static methods are useful for common or shared class functionality. In this case, the describe() method is used to describe what the Person class is. It will apply to every instance of Person. This is why we make it a static method.

Class Inheritance

Inheritance allows you to create new classes based off existing ones. These new classes “inherit” the methods and properties of their parent. They can also override or extend the parent:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }


  static describe(){

    console.log("This is a person.")

  }


  sayName() {

    console.log("My name is " + this.name)

  }

}



class Programmer extends Person {

  sayName(){

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



averageJoe.sayName()


//logs 'My name is Todd'


programmer.sayName()


//logs 'My name is Sam and I am a programmer!'

Using the extends keyword, we can create a new class sharing the same characteristics as Person. Notice how we override the sayName() method with a new definition for the Programmer class. Apart from overriding this method, everything else remains the same for both Person and Programmer.

Using super

The super keyword allows a child class to invoke parent class properties and methods.

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}





class Programmer extends Person {

  sayName(){

    super.sayName()

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



programmer.sayName()



//logs 'My name is Sam'

//logs 'My name is Sam and I am a programmer!'

Notice how we call super.sayName() in the Programmer implementation of sayName(). While this invokes the parent implementation of super.sayName(), the name property still references the Programmer class.

Conclusion

Classes facilitate object oriented programming in JavaScript. While regular objects provide similar functionality, classes provide the extra advantage of inheritance and static methods.

Getting Started with React Native in 2020: Build Your First App

Getting Started with React Native in 2020: Build Your First App

Getting Started with React Native in 2020: Build Your First App. How To Code Your First Mobile App Using React Native. Learn how to build your first React Native app with important basic concepts. Learn the basics of React Native, a JavaScript Native Mobile App compiler. We look into components, events, props and passing them and more.

How To Code Your First Mobile App Using React Native

Learn how to build your first React Native app with important basic concepts

Today we start off with the basics of React Native, a javascript native mobile app compiler. We look into components, events, props and passing them and more.