How much JavaScript do you need to know before going to Reactjs?

Share Your Love

Know before going to Reactjs, If you are already familiar with some Javascript ideas, learning ReactJS shouldn’t be that tough. One of the fascinating things about utilising ReactJS is that it helps you become more proficient in JavaScript, but before you decide to give it a go, make sure you comprehend these JavaScript ideas.

One error people make when learning a framework or library is failing to consider the contributions it makes. These are the subjects we will be addressing before we begin. Even though some of these subjects aren’t specifically connected to reactjs, you’ll probably encounter them frequently in a react codebase. Be aware that the majority of these subjects relate to es6 and es-next javascript features.

  • Let and Const
  • Ternaries
  • Template Literals
  • Shorthand Properties
  • Rest/Spread
  • Destructuring
  • Default Parameters
  • ES Modules
  • Short circuit Evaluation
  • Higher Order Functions (Array Methods)
  • Nulish Coalescing Operation
  • Optional Chaining
  • Arrow Functions

Introduction

With the help of the open-source React js library, we can create component-driven, declarative websites quickly. You can create desktop apps (electron, node gui), cross-platform mobile apps (react native), and progressive web apps with react js (pwas). Therefore, knowing React is important since you can apply your skills to constructing many other things.

For instance, if you wanted to obtain the list of users and display the proper loading or errors in standard Javascript, you may do something like this.

<button onclick='displayData'> see users </button>
<div id='users'>
</div>
<div id='loading'>
</div>
<div id='error'>
</div>
const usersUI = document.getElementById("users");
const loadingUI = document.getElementById("loading");
const errorUI = document.getElementById("error");
const apiUrl = "https://jsonplaceholder.typicode.com/users";

// fetch data from an api
const fetchData = async () => {
const res = await fetch(apiUrl);
return await res.json();
};

// display your data to the ui
const displayData = async () => {
errorUI.innerHTML = "";
loadingUI.innerHTML = "Loading...";

fetchData()
.then((users) => {
usersUI.innerHTML = users.map((item) => &lt;p>$ {item.name}&lt;/p>);
})
.then(() => (loadingUI.innerHTML = ""))
.catch(() => {
loadingUI.innerHTML = "";
errorUI.innerHTML = "Error fetching data";
});
};
const usersUI = document.getElementById("users");
const loadingUI = document.getElementById("loading");
const errorUI = document.getElementById("error");
const apiUrl = "https://jsonplaceholder.typicode.com/users";

// fetch data from an api
const fetchData = async () => {
const res = await fetch(apiUrl);
return await res.json();
};

// display your data to the ui
const displayData = async () => {
errorUI.innerHTML = "";
loadingUI.innerHTML = "Loading...";

fetchData()
.then((users) => {
usersUI.innerHTML = users.map((item) => <p>$ {item.name}</p>);
})
.then(() => (loadingUI.innerHTML = ""))
.catch(() => {
loadingUI.innerHTML = "";
errorUI.innerHTML = "Error fetching data";
});
};

Consider how we begin by making the api, setting the proper UI from the function, and targeting the components from the html. If we then have up to 100 UIs to update on the screen, this will quickly become spaghetti code. In contrast to our react version, we establish the application state using a language called jsx that looks like HTML.

Let and Const

When declaring a variable in javascript, the keywords let and const are similar; let implies that the variable can still be assigned to another value, whereas const indicates that the value specified there is the final value.

let favNumber = 7;
const LargestSea ='The Indian Ocean'

It is still possible to reassign favNumber without any problems, but reassigning LargestSea will result in a parser error, Assignment to constant variable.

Ternaries

In programming, ternaries are a more concise way to declare an if-else statement. Creating a function to determine whether an integer is even, for instance;

function isEven(input)
{
  const even = n % 2 == 0;
  if(even) 
  {
      return true
  } 
  else 
  {
      return false
  }
}

Is it possible to rewrite this as input% 2===0? The expression input% 2===0 checks for true:false and verifies if? It instructs what to put in the else output and indicates the output if the statement is true.

A useful illustration is adding className or style only when necessary when carrying out an activity.

<div className={success?'success-item' :'item'}>
Items List
</div>

Multiple nested ternaries are possible, but it’s not recommended because it makes the code harder to read.

Template Literals

The use of template literals in a javascript expression allows for a smoother concatenation of objects. Its structure is as follows: $variable other texts. It begins by declaring backticks, then comes the $ sign and curly brackets, it’s structure looks like this, ${variable} other texts. Consider, for instance,

if you set the age to 10, you will likely concatenate like,

const ageOutput = 'You are ' + age + ' years old'

We can do better by writing something like this in a template literal, const ageOutput = `You are ${age} years old `. Take a look at how tidy that is. A useful example in React is to imagine that the div below has several classes as well. If you write “item-section first-section” beside the curly brackets to indicate that this is a string, it will function flawlessly without the requirement for concatenation.

<div className={ $ {success?'success-item' :'item'} item-section first-section}>
Items List
</div>

Shorthand Properties

Take the sample object we have, for instance.

const name = "Lingaraj"
let user = { name:name }

We can also represent this to  let user= {name}

note, that ‘name’ is now singular inside the object.

Rest/Spread

If you join or copy arrays then Rest/Spread is an es6 feature in javascript. It begins with “…” three dots followed by what you want to join or copy.

assuming we have sample data, for instance,

Objects

const user  = {
  name:'Sonu',
  age:12
}

const otherProperties = {
hobby:'hiking',
bestColor:'red'
 }

If you join together before es6, then the Object.assign method is used

The Object.assign() helps you to copy

The Object.assign() method allows you to copy all from one or more source objects to one or more target objects, enumerable own properties, and return the target object, Object.assign(target, user, Obj2, Obj3, ...) :

let finalMerge = Object.assign({}, user, otherProperties)

console.log(finalMerge) // { name: 'Tony', age: 12, hobby: 'hiking', bestColor: 'red' }

using the spread operator we can simply just put it this way, let finalMerge = {...user, ...otherProperties}

Arrays

Take an example of two sample arrays,

const permissions = ['view user', 'view reports', 'download reports']
const otherPermissions = ['initiate transactions', 'delete user']

The array concat method, const finalArray = permissions, was available until es6. concat(otherPermissions) would give us something like this [‘view user’, ‘view reports’, ‘download reports’, initiate transactions’, ‘delete user’]. Using the spread operator will help us perform better,

const finalMerge = [...permissions, ...otherPermissions]

Destructuring

Destructuring is a technique for more understandable and orderly access to the values contained in an object or array.

Object Destructuring

const person ={
  favNumber:'green',
  name:'Mike',
  cars:['mercedes', 'toyota']
}

Before ES6, we must first assign each property to a variable if we wish to access the individual attributes contained in the person object;

const favNumber = person.favNumber;
const name = person.name
const cars = person.cars

With object destructuring, we could carry out the following:

const { favNumber, name, cars } = person
console.log(favNumber, name, cars) // green, Mike, ['mercedes', 'toyota']

Take a look at how we may obtain the values without having to assign them again. If we wish to immediately rename the name property on the person object after destructuring, for example, we can still do some things with object destructuring.

const {name:realName, favNumber, cars} = person,
console.log(realName) // "Mike".

What happens if we destructure an object and decide to assign it a default value even if we are unsure if this feature is now present on the object?

const {name, favNumber, cars, favFood='Mottor Paneer'} = person
console.log(favFood) // 'jollof rice'

Even nested objects can be destructured, for example

const customer = {
name:'Tom',
mobile:078 7070 2325,
email:tomfield@email.com,
address:{
country:'UK',
city:'East Davoch',
zipCode:AB34,
street:'33 Guildford Rd'
 } 
}

We might destructure it to obtain the customer country,

const {address: { country } } = customer
console.log(country) // UK

Let’s talk more about the rest operator. Most of the time, we use both interchangeably; particularly, we use ‘rest’ to copy part or the whole of an array or object. In our last article, we discussed ‘rest/spread’.

const {cars, favNumber, ...otherObj} = person
console.log(otherObj) // {name:'Mike'}

The remainder of the item is copied for our usage. practical react illustration

const HeaderComponent = ({title, ...restProps})=>{
return <div {...restProps}> {title} </div>
}

By using our HeaderComponent in this way, we can apply the “my-item” class as if we had manually added it to the component itself:

<HeaderComponent className="my-item" />

function Argument Destructuring

When using an object that is being passed as an argument to a function, its structure can be removed. For instance,

let car = {name:'Tesla', color:'red'}

function getCar({name, color}){
return Your car is ${name} with the color ${color}
}

We can destructure the parameter to the getCar function since we already know what to expect.

Array Destructuring

Destructuring an array function similarly to destructuring an object. Let’s have a look at some sample data below as an example.

const users = ['Lingaraj', 'Sangram', 'Rahul', 'Sonu']
const [a,b, ...others] =users

console.log(a,b, others) // 'Lingaraj', 'Sangram', ['Rahul, Sonu']

The useState function in React provides a practical example.

import {useState} from 'react'
const [loading, setLoading] = useState(false)

Default Parameters

If a function argument is missing when it is called, default parameters let us provide a default value for it. For instance;

function greetUser(username='user'){
return Welcome ${username}, hope you bought some pizzas
}

const greetingsOne = greetUser('Greg')
console.log(greetingsOne) // 'Welcome Sam, hope you bought some burger'

const greetingsTwo = greetUser()
console.log(greetingsTwo) // 'Welcome user, hope you bought some burger'

Note, the difference between the two greetings, in the second greeting, the username is returned as ‘user’ because that’s what we passed as the default value.

ES Modules

The export keyword in Javascript scripts used to expose values required from other files or locations is known as an ES Module. It’s important to note that while commonjs has been there for a while, the adoption of ECMAScript (a JavaScript standard intended to ensure that web pages work with different web browsers) has paved the way for browsers to parse and load javascript files.

ES Module

person.js

export const person = {
  name:'Lingaraj',
  color:'yellow'
}

user.js

import { person } from 'person.js'
console.log(person) // { name:'Lingaraj', color:'yellow' }

The export keyword in Javascript scripts used to expose values required from other files or locations is known as an ES Module. It’s important to note that while commonjs has been there for a while, the adoption of ECMAScript (a JavaScript standard intended to ensure that web pages work with different web browsers) has paved the way for browsers to parse and load javascript files.

import { person as currentPerson } from "./person.js";
console.log(currentPerson) // { name:'Lingaraj', color:'yellow' }
console.log(person) // 'person is not defined'

Default Export

With default exports, a js file can only disclose one value to the outside world. The export default “value” keyword is used to signify it and is typically found at the end of the file or right after it is declared. A default export can only be used once in a file before throwing a parser error;

colors.js

const colors = ['red', 'blue', 'green', 'orange']
export default;

views.js

import colorList from './colors.js'
console.log(colorList) // '['red', 'blue', 'green', 'orange']'

We could have called the file “colorList” or “colorsArray” and it would have worked just fine since when a file is exported by default, you can import it with any name you wish.

Short Circuits

Short circuits analyse expressions from left to right until it is determined that the conditions that have already been examined won’t affect the conditions that are still to be evaluated, hence avoiding unnecessary work and resulting in efficient processing. Two operators are supported by short circuits: (&&) AND and (||) OR.

AND( && )
true && 'Hello' -> This outputs 'Hello'
true && true && false -> This outputs 'false'

false && true -> This outputs 'false'
(true && false) && false -> This outputs 'false'

OR ( || )

true || false -> This outputs true

false || 'hello' || false -> This outputs 'hello'

Practical react usage

import {useState, useEffect} from 'react';

const Items = ()=>{
const [loading, setLoading] = useState(false)
const [data, setData] = useState([])
async function ladData(){
const response = await (await fetch('http://dataBaseUrl')).json()
setData=(response)
setLoading(false)
}
useEffect(()=>{
setLoading(true)
loadData()
},[])
return (

<div>
  {loading && "Loading"} // while loading is true shows 'Loading...'
  {data.lengtht && data.map((item) => <p key={item.id}> {item.sampleName} </p>)}
  // if data.length is truthy, ie, it's length is greater than 1 // then go
  ahead to ahead to show list in the UI
</div>
) }

When utilising short-circuit for conditional rendering, be careful because values like zero and undefined can lead to odd UI behaviours.

for instance,

const Todos = ()=>{

const list = []
return (

<div>
  {list.length && list.map((todo) => <p key={todo.id}> {todo.title} </p>)}
</div>
) }

Guess what will be listed on the to-do list? “0“. Yes, JavaScript interprets a value of zero or undefined as a false value. The list.length can be typecast to boolean as one approach to resolve this,!! Such an error would not have occurred if list.length or Boolean(list.length) had been used.

Higher Order Functions (Array Methods)

Higher order functions (HOFs) are functions that return another function or accept another function as an argument or set of arguments.

The likelihood is that you have used it at least once or more secretly. Commons one you may be using are;

  • Find
  • Filter
  • Map
  • Includes
  • Reduce

other notable mentions here, some, every.

const users = [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"lifeTimePurcahse":4000
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"lifeTimePurcahse":78200

    },
    {
      "id": 3,
      "name": "Clementine Bauch",
      "username": "Samantha",
      "email": "Nathan@yesenia.net",
      "phone": "1-463-123-4447",
      "website": "ramiro.info",
      "lifeTimePurcahse":600
    },
    {
      "id": 4,
      "name": "Patricia Lebsack",
      "username": "Karianne",
      "email": "Julianne.OConner@kory.org",
      "phone": "493-170-9623 x156",
      "website": "kale.biz",
      "lifeTimePurcahse":10000
    },

]

Find

The element that meets the testing function is returned by the find method, which accepts a function as an input.

function checker(item){
return item.id == 1
}

users.find(checker) // or users.find((item)=> item.id ==1) both functions returns the same output
// {
//"id": 1, "name": "Leanne Graham", "username": "Bret","email": "Sincere@april.biz",
// "phone": "1-770-736-8031 x56442", "website": "hildegard.org","lifeTimePurcahse":4000
// }

Filter

The filter method returns a new array that is made up of the elements that passed the test set up by the callback function. There is no modification or alteration of the basic array.

const userPurchases = users.filter(user => user.lifeTimePurchase > 70000)
// only user with id 2 has lifetimePurchase greater than 70,000
console.log(userPurchases)
// [ {
// "id": 2,
// "name": "Ervin Howell",
// "username": "Antonette",
// "email": "Shanna@melissa.tv",
// "phone": "010-692-6593 x09125",
// "website": "anastasia.net",
// "lifeTimePurcahse":78200
// }]

An array containing the filtered results will always be returned by filter.

Map method

The callback function’s condition is satisfied by the new array of objects that the map method returns. In the end, it also modifies the initial array.

const userIds = users.map((user, index)=> user.id)
console.log(userIds) // [1,2,3,4]

Includes

The include method returns a boolean result of true or false and is used to determine whether a given item is contained in an array.

const userIsPresent = users.map(i=> i.id).includes(1)
console.log(userIsPresent) //true

Reduce Method

In order to return a single value, the reduce method accepts a reducer function.

The reduced method’s anatomy is shown below;

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

function reducerFunc(total, currVal, currIndex, arr){
// currIndex -> Current Index during iteration
// arr -> The whole
// total -> current total on each iteration
//currVal -> Current value on each iteration

return total + currVal.lifeTimePurchase

}
// we are setting zero as the initial value of total
const totalLifeTimePurchases = users.reduce(reducerFunc,0)

console.log(totalLifeTimePurchases) // 92800

Let’s look at a Higher Order Functions example using React;

const users =()=>{
const currentUserId=3
const vipUserPurchase = 10000
const raffleUserWinners = [1,4,3]

// map
const _users = users.map(user => (<p key={user.id}> {user.username} </p>))
function reducerFunc(total, currVal){
return total + currVal.lifeTimePurchase
}

//reduce
const totalLifeTimePurchases= users.reduce(reducerFunc,0)

// find
const currentUser = users.find(user=> user.id== currentUserId)

//filter
const vipList = users.filter(user=> user.lifeTimePurchase >= vipUserPurchase)

// includes
const isRaffleWinner = users.map(user=>user.id).includes(currentUserId)

return (

<div>
{_users}
<p>Total Purchase: {totalLifeTimePurchases} </p>
<p>current user: {currentUser.username} </p>

    <h4> vip list <h4>
    {
      vipList.map(user=> <p key={user.id}> {user.username} </p>)
    }

    raffle status: {isRaffleWinner ? 'Congrats, you're a raffle winner' : 'Oops! Try again later'}

    </div>)

Nulish Coalescing Operation

When the left side operand is null or undefined, nullish coalescing operations(??) enables us to return the right hand operand;

const a =12
const b = 50;

a ?? b // -> 12

let c;
let d =45
c ?? d // -> 45

Optional Chaining

Optional chaining(?.) enables us to safely access an object’s key or call functions when we’re uncertain of their availability.

let user = {
name: "Joe",
details: { age: 82 }

};
const userTown= user?.address?.town;
console.log(userTown); // undefined
const user.fullInfo?.() // undefined

Arrow Functions

Another method of declaring functions in javascript is with arrow functions, often known as fat-arrows. They do act differently when handling this, and they do bind to the parent class’s/this object’s execution context. However, as react currently favours hooks over es6 classes, we do not need to worry too much about this. This function must be explicitly bound to the parent components by the user. Additionally, they offer a quick and implicit method for returning values from a function.

const sum = (a + b)=> a+b
const sqaure = (a)=> a**2
// can even be shortened to square = a =>a**2, when we have a singular argument.

// this is the same as

function sum(a,b){
return a + b;
}
//sum()

function square(a){
return a**2
}

// React Example
function List({List=[]}) {
return (

<ul>
  {list.map((item) => (
    <li key={item.id}>{item.name}</li>
  ))}
</ul>
) } 

Conclusion

After becoming familiar with the fundamentals of javascript, learning reactjs shouldn’t be difficult. You simply need to be familiar with the principles that are utilised in a react application the most frequently. Learning about these subjects will undoubtedly increase your comfort level when you begin to study reactjs.

You can also study ES6 classes and async/await, which are both noteworthy.

Thank you for reading, and I’ll see you in the future one!

I collect this Information from https://dev.to/okeken/javascript-to-know-for-reactjs-5e34

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 355

Newsletter Updates

Enter your email address below to subscribe to our newsletter