Skip to content

Instantly share code, notes, and snippets.

@ketanghumatkar
Created June 23, 2019 14:52
Show Gist options
  • Save ketanghumatkar/736997c49a83ba908c0933c4cb99f9ab to your computer and use it in GitHub Desktop.
Save ketanghumatkar/736997c49a83ba908c0933c4cb99f9ab to your computer and use it in GitHub Desktop.
ES6 syntax used in react.js

Use of ES6 in React

Declairation of class

class Developer {
  constructor(name) {
    this.name = name;
  }

  hello() {
    return 'Hello everone. I am' + this.name;
  }
}


var dev = new Developer('Ketan');
dev.hello();

Inheritance of class

class ReactDeveloper extends Developer {
  installReact() {
    return 'Installing react...'
  }

  hello() {
    return 'Hello everone. I am' + this.name + 'I am React Developer';
  }
}

var dev = new Developer('Ketan');
dev.hello();
dev.installReact();

Arrow function

const testFunction = (firstName, lastName) => {
  return firstName + lastName;
}
const oneFunction = name => {
  return name;
}
const secondFunction = name => 'I am here!'
const HelloWorld = (props) => {
  return <h1>{props.name}</h1>
}

Destructuring assignment for objects

const developer = {
  firstName: 'K',
  lastName: 'G',
  developer: true,
  age: 28,
}

const {firstName, lastName} = developer
console.log(firstName);

const {firstName: fname} = developer
console.log(fname);

Destructuring assignment for arrays

const numbers = [1,2,3,4];
const [one, two] = numbers;
// one = 1, two = 2

const [one, two, , four] = numbers;
// one = 1, two = 2, four = 4 
const HelloWorld = ({hello}) => {
  return (
    <h1>{hello}</h1>;
  )
}
import React, { Component } from 'react';

class App extends Component {
  // class content
  render(){
    const users = [
      { name: 'Nathan', age: 25 },
      { name: 'Jack', age: 30 },
      { name: 'Joe', age: 28 },
    ];

    return (
      <ul>
        {users
          .map(user => <li>{user.name}</li>)
        }
      </ul>
    )
  }
}

ES6 module system

import React, { Component } from 'react';
export default App;
touch utils.js

// utils.js
export times(x) {
  return x * x;
}

export plusTwo(x) {
  return x + 2;
}

import {times, plusTwo} from './utils';

console.log( times(2));
console.log(plusTwo(3));
// utils.js

export default function(x) {
  return x * x;
}

// app.js
import k from './utils';

console.log(k(4)); // returns 16
// in util.js
export function times(x) {
  return x * x;
}

export function plusTwo(number) {
  return number + 2;
}

// in app.js
import { times as multiplication, plusTwo as plus2 } from './util.js';
// default and named import together
import React,  { Component } from 'react';

spread operator

const numbers = [1,2,3,4];

const sum = (x, y, z) => {
  return x + y + z;
}
console.log(sum(...numbers));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment