ES6 with Javascript Concepts for React JS

shubhamtiwari909

Shubham Tiwari

Posted on December 17, 2022

ES6 with Javascript Concepts for React JS

Hello Everyone today i will discuss few concepts which you should know before moving onto React JS.

Let's get started...

ES6 Arrow Functions -

  • Arrow function allows you to create functions with cleaner code and more readable format.
  • Arrow function can return a statement both implicitely or explicitely.
  • Syntax for arrow function
function regularFunction(num){
  return num
}

const arrowFunction = (num) => num

// React JS
const App = () => {
  const user = 'Guest';

  return (
    <><h1>Hello World</h1></>
  );
}

Enter fullscreen mode Exit fullscreen mode

Template Literals -

  • It is used to embed js variables or expression inside strings in a more readable and cleaner way.
const price = "12.00$";

// Normal string with double quotes
const normalString = "You bill is: " + price

// Template literal
const templateLiteral = `You bill is: ${price}`
Enter fullscreen mode Exit fullscreen mode
  • Template literal is used with backtick(key below Esc) and for putting the js expression we have to use this notation ${}, inside the curly bracket you can pass any js expression or variable.

map, reduce and filter -

  • These are the array methods which is commonly used in React Components for manipulating the data inside the array and render the UI with that data.
const data = [1,2,3,4,5,6,7,8];

// map method - Multiplying all the numbers by 2
const mapping = data.map(item => item*2)
// [2,4,6,8,10,12,14,16]

//filter method - Return all the numbers greater than 5
const filtering = data.filter(item => item > 5)
// [6,7,8]


// Reduce method - Going through all the numbers and adding them and return the sum of all 
const reducing = data.reduce((previous,current) => previous + current,0)
// 36
Enter fullscreen mode Exit fullscreen mode
// React JS
import React, { useState } from 'react';
const heroes = [
  {
    id: 100,
    name: 'Ironman',
    strength: 910,
  },
  {
    id: 101,
    name: 'Hulk',
    strength: 780,
  },
  {
    id: 102,
    name: 'Thor',
    strength: 10000,
  },
];
export function App(props) {
  const [superHeroes, setSuperHeroes] = useState(heroes);

  const combineStrength = heroes.reduce((previous,current) => previous + current.strength,0);

  return (
    <div className='App'>
      {superHeroes
        .filter(hero => hero.strength > 800)
        .map(hero => {
          return (
            <div key={hero.id}>
              <h1>Hello I am {hero.name}</h1>
            </div>
          );
        })}

        <p>Combine Strength: {combineStrength}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Ternary Operator -

  • It is used to check the single line conditionals and we can use it in place of you if-else statement as it is more readable and cleaner approach.
const superhero = "Ironman";

// Ternary operator with ? and :
// If the condition is tru execute the statement after the ? and if it is false execute the state after :
const universe = superhero === "Ironman" ? "Marvel Universe" : "DC Universe";
// Marvel Universe

// React js
import React, { useState } from 'react';

export function App(props) {
  const [superHero, setSuperHero] = useState("Ironman");


  return (
    <div className='App'>
     <h1>{superHero === "Ironman" ? "Shoot Repulsors" : "Hulk Smash"}</h1>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • It is quite easy to use and is used to render the UI conditionally in React JS.

Import and Export Statements -

  • It is also a feature of ES6 where we can create multiple js files as components and can import them somewhere else
  • For importing the variable or function we have to use the "import" keyword and for exporting we have to use the "export" keyword.
// Superhero.js
export const superhero = "Thor"

// App.js
import {superhero} from './Superhero'
Enter fullscreen mode Exit fullscreen mode
  • As you can see we have exported the variable superhero and imported it in other file, i have used the curly brackets because it is a named export , if is a default export , we can remove the curly brackets.
  • These works same in React JS
  • For full reference visit here - https://blog.yogeshchavan.dev/es6-import-and-export-cheatsheet

async / await -

// React JS
import React, { useState, useEffect } from 'react';

function App() {
  const [users, setUsers] = useState([]);

  const getUsers = async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos')
    if (!response.ok) {
      throw new Error('Data coud not be fetched!')
    } else {
      return response.json()
    }
  };
  useEffect(() => {
   getUsers().then(response => setUsers(response))
  }, []);

  if (!users) return <div>Loading...</div>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.title}</li>
      ))}
    </ul>
  );
}
export default App
Enter fullscreen mode Exit fullscreen mode

Higher Order Function -

  • Higher order function return another function from inside or take another function as an argument.
let debounce = (fn, delay) => {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn();
    }, delay);
  };
};
Enter fullscreen mode Exit fullscreen mode

Object Destructuring -

It is used to extract Array items or object property values and assigning them to variables.

const array = ["Ironman","Thor","Hulk"]
const superHero = {
  Marvel:"Ironman",
  DC:"Batman"
}
// array destructuring - will assign the value of 3 items in the array to these variables
const [ironman,thor,hulk] = array

// Object destructuring
const {Marvel,DC} = superHero

// React JS hooks example
const [user,setUser] = useState("Username")
// user is the state which stores the value and setUser is the //callback which changes the state or say value of the user
Enter fullscreen mode Exit fullscreen mode

Spread and Rest operator

  • They both have the same notation "...", three dots, but works differently
  • In destructuring it works as rest operator spreading the remaining values of the array into single variable and inside functions or parameters it works as spread operator to spread the single value as array or object.
  • They both work similar in React JS.
  • For full reference visit here - https://www.freecodecamp.org/news/javascript-rest-vs-spread-operators/

THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

^^You can help me by some donation at the link below Thank you๐Ÿ‘‡๐Ÿ‘‡ ^^
โ˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/css-iswherehas-and-not-2afd

https://dev.to/shubhamtiwari909/theme-changer-with-html-and-css-only-4144

https://dev.to/shubhamtiwari909/swiperjs-3802

https://dev.to/shubhamtiwari909/going-deep-in-array-sort-js-2n90

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
shubhamtiwari909
Shubham Tiwari

Posted on December 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About