Introduction
So, you've decided to learn React. But as React is written in JavaScript and uses JavaScript, you've to learn some most used JavaScript concepts in React in order to learn and master React. In this post, I'm going to teach you 9 most used JavaScript concepts in React
Disclaimer: This list does not include JavaScipt A-Z but the most used concepts in React
1. HOF: Map, Filter, Reduce
HOF stands for Higher Order Functions and: map, filter, and reduce is what 90% used HOF functions in React that operate on arrays and knowing them is not choice but requirement for React
map
Map HOF is used to return different array with the same length as the original array. New array items are decided by what's returned within map function body.
In React map used to create array of elements
const numbers = [2, 5, 9, 50]
const newNumbers = numbers.map(number => number * 2)
console.log(newNumbers) // [4, 10, 18, 100]
/**
React: This is the example that creates array of elements and returns them
*/
const ReactComponent = ({array})=>{
return <ul>{array.map(item => <li key={item.id}>{item.text}</li>)}</ul>
}
filter
Filter HOF is used to filter out any array item that does not pass the test which is set up in function body and return only items that passed the test in the new array. Basically you can filter out any item by setting boolean test
const ages = [9, 15, 29, 5, 44];
const filteredAges = ages.filter(age => age >= 18)
console.log(filteredAges) // [29, 44]
/**
React: This is the example that filters out students that are less than 18 and returns all students over or equal to 18
*/
const ReactComponent = ({students})=>{
return (
<div>
<h1>Students aged over 18</h1>
<ul>
{students.filter(student => student.age >= 18).map(student => <li key={student.id}>{student.name}</li>)}
</ul>
</div>
}
reduce
Reduce HOF is used to reduce array items into single value. It's very useful when we need to sum array items, or reduce items into single value.
const numbers = [5, 20, 10, 5]
const sum = numbers.reduce((total, currEl)=> total + currEl, 0)
console.log(sum) // 40
/**
React: In this example, we sum total total spending
*/
const ReactComponent = ({expenses})=>{
return (
<div>
<h1>Your total spending</h1>
<p>Total expenses: {expenses.reduce((total, currEl) => total + currEl.spend ,0)}</p>
</div>
2. Object Destructuring
Object Destructuring as name suggests lets us destructure copy of the object properties and reuse them without including object name. When destructing, you can only destructure by existing object property name, other giving default property name and value. And there's not order of destructuring of object properties which means you can destructure last object property first and first object property last.
const person = {
name: "Jaxongir",
age: 27,
hobbies: ["Reading", "Calisthenics", "Cooking"]
}
const {name, age, hobbies} = person;
console.log(name) // Jaxongir
console.log(age) // 27
console.log(hobbies) // ["Reading", "Calisthenics", "Cooking"]
/**
We can also rename destructured property and also assign default value. Default value used in case of missing property value or missing property altogether.
*/
const person = {
hobbies: ["Reading", "Calisthenics", "Cooking"]
}
const {name: firstName = "John", age: hisAge = 18, hobbies} = person
console.log(firstName) // John
console.log(hisAge) // 18
console.log(hobbies) // ["Reading", "Calisthenics", "Cooking"]
/**
We can go as deep as needed when destructuring
*/
const testObj = {
first: "Child 1",
parent: {
second: "Child 2",
parent: {
third: "Child 3",
}
}
}
const {first, parent: {second, parent: {third}} } = testObj;
console.log(name1) // Child 1
console.log(name2) // Child 2
console.log(name3) // Child 3
/**
React: In this example one component passes props to child component and we destructure those passed props.
*/
const ChildComponent = ({name, age, country})=>{
return (
<div>
<h1>Name: {name}</h1>
<h1>Age: {age}</h1>
<h1>Country: {country}</h1>
</div>
)
}
const ParentComponent = ()=>{
return <ChildComponent name="Jaxongir" age="27" country="Uzbekistan"/>
}
3. Array Destructuring
Array destructuring works nearly the same as the object destructuring but as array is ordered data structure, you've to desctructure the array items in order as they appear in array.
const names = ["Jaxongir", "Elisabeth", "Sarah"]
const [jaxongir, elisabeth, sarah] = names;
console.log(jaxongir) // Jaxongir
console.log(elisabeth) // Elisabeth
console.log(sarah) // Sarah
// breaking order of destructuring
const names = ["Jaxongir", "Elisabeth", "Sarah"]
const [elisabeth, jaxongir, sarah] = names;
console.log(jaxongir) // Elisabeth
console.log(elisabeth) // Jaxongir
console.log(sarah) // Sarah
// desctructuring nested array
const nestedArray = [1,[2,[3,[4,[5]]]]]
const [first, [second, [third, [fourth, [fifth]]]]] = nestedArray
console.log(first) // 1
console.log(second) // 2
console.log(third) // 3
console.log(fourth) // 4
console.log(fifth) // 5
// you can skip certain indexes by typing ,
const numbers = [1,2,3,4,5]
const [first, , , , fifth] = numbers;
console.log(first) // 1
console.log(fifth) // 5
4. Spread Operator
Spread Operator spreads out or copy object properties to another object or array items to another array
NOTE: you might confuse spread with the rest operator. One thing to remember is that spread operator always be used on the right hand side of = operator and the rest operator will be used on the left hand side of = operator.
const arr1 = [1,2,3]
const arr2 = [4,5,6]
const combinedArr = [...arr1, ...arr2]
console.log(combinedArr) // [1,2,3,4,5,6]
5. Rest Operator
Rest Operator is used to copy the rest of the object properties to another object or array items to another array or array items from the passed argument, desctructuring object, desctructuring array
const numbers = [1,2,3,4,5,6]
consst [first, ...restNumbers] = numbers
console.log(first) // 1
console.log(restNumbers) // [2,3,4,5,6]
6. Ternary Operator
Ternary operator is the shortand syntax of if else and most often used when code in if and else body is single statement
let age = 17
age >= 18 ? console.log("You are allowed to drink") : console.log("You are under age")
7. Shorthand Conditional
Shorthand conditional with && is used to check if value on it's left true, always execute value to it's right.
NOTE: Be careful if value to it's left is a number and evaluates of 0 if such it returns 0 instead of displaying nothing
let age = 18;
age >= 18 && console.log("You are allowed to drink")
/**
when using array don't use array.length coz if array is empty, it returns 0 instead of nothing so compare length instead
*/
const numbers = []
numbers.length && numbers.map(number => number + 50) // 0
/**
React: Example demonstration of ternary operator
*/
const Component = ({students})=>{
return students.length > 0 ? <StudentList students={students} /> : <h1>Data being fetched...</h1>
}
8. Template Literals
Template Literals allows us to insert JavaScript expression and produce new expression. In the end that expression is converted into string
const printFullInfo = (name, age, country)=>{
console.log(`His name is ${name} and is ${age} years old. And he is from ${country}`)
}
printFullInfo("Jaxongir", 27, "Uzbekistan")
9. Callback Functions
Callback Functions are just normal function which is passed to as argument to another function and invoked by that function.
In React callback functions are primary uses of invert data flow, child to parent data passing or action.
const mapCustom = (arr, callbackFunc)=>{
const newArr = [];
for(let i = 0; i < arr.length; i++){
newArr.push(callbackFunc(arr[i]))
}
return newArr;
}
mapCustom([1,2,4], (number)=> number * 2) // [2,4,8]
/**
React: Example demonstration of passing callback function to child component to retrieve data back
*/
const ChildComponent = ({getId})=>{
return <button onClick={()=> getId("id placeholder")}>Button</button>
}
const ParentComponent = ()=>{
const getId = (id)=>{
alert(id)
}
return <ChildComponent getId={getId}/>
}