10 JavaScript concepts for React beginners - With Code Samples
A shortlist of important Javascript concepts for React Developers - With Code Samples.
Hello Coders!
React is a Javascript frontend library and if you want to get started with React
first you have to learn Javascript, the programming language that powers React
. Javascript
itself is a huge language, and it’s not possible for you to learn all of it before learning React. But fear not, this article explains 10 Javascript
concepts you must learn before moving on to React
.
Thanks for reading! Topics covered:
- 👉
What is Javascript
- Short info - 👉
Introduction to React
- 👉 #1 -
Variables
- 👉 #2 -
Functions Definition
- 👉 #3 -
Classes and the Extend keyword
- 👉 #4 -
Async/Await
- 👉 #5 -
Array methods
- 👉 #6 -
Ternary Operator
- 👉 #7 -
Template Literal
- 👉 #8 -
Destructuring
- 👉 #9 -
Spread Operator
- 👉 #10 -
Import and Export
- 👉 Code a
Hello World
in React
✨ What is JavaScript
JavaScript is a high-level scripting language for web pages. It was invented by Brendan Eich in 1995. At first JavaScript’s work was to make the web page interactive. but later developers built frameworks, and libraries to make JavaScript available almost on all platforms.
For instance, you can build a mobile app with react native, a desktop app with electron. backend with node.js and frontend with react.js etc.
These are just a few things I mentioned JavaScript is capable of doing. if I say all the things javascript is capable of doing it will be an article itself.
With that said, let’s move on and see what React is.
✨ What is React?
React.js
is an open-source JavaScript front-end library created and maintained by Facebook. It’s a component-based library, which means React breaks down a bigger application into smaller pieces named components. This approach makes building and managing bigger projects easier.
In case this is your first contact with React, you should note that React is a library, and not a framework like Angular.js, which means it’s not a complete solution. When building apps with React you need to use external libraries for things like routing, HTTP requests, and state management.
This is the short intro to react. if you wanna learn more I’ll put a few free resources at the end of the article. go check them out.
Enough of the definitions, now, let’s get to the JavaScript concepts you need to learn before learning React.
✨ Variables
Before getting started with React, you must how to declare a variable in javascript. You can declare variables in javascript in three ways. using var, let, or const. each of them has pros and cons.
var foo = "hello world!";
let bar = "Hey, There!";
const baz = "What's up?";
There’s a quiet difference between these three. Because the “var” type will make the variable visible in the global scope, “let” or “const” is recommended.
To learn more about each definition feel free to access a full tutorial that covers in deep of the differences:
freecodecamp.org/news/var-let-and-const-wha..
✨ Functions Definition
React’s fundamental rule is to break a bigger project into smaller components. And those components are either Functions or Classes.
So, knowing how to declare a function with JavaScript is very important. Also as with the variables, there are more than 2 ways to declare a function. but these 2 are the most important:
Function declaration
Arrow Function
Let's see the examples of each one.
Function Declaration
// function declaration
function add(num1, num2) {
return num1 + num2;
}
add(2, 2) // 4
This is how you would declare and call a function in plain Javascript.
Now that you know how to declare a simple function with javascript, let’s see how it is used in React.js. In React functions are used to create functional components.
function App() {
return (
<div className='App'>
<h1>Hello world!</h1>
</div>
);
}
This is the use of function declaration in React. As you can see a component does not return any value, it returns the HTML which determines how the application will look.
Arrow Function
// Arrow function
const subscract = (num1, num2) => {
return num1 - num2;
}
subscract(5, 2) // 3
The arrow function is just a little cleaner than the function declaration. there’s not much difference between these two. Example of functional components:
const App = () => {
return (
<div className='App'>
<h1>Hello world!</h1>
</div>
);
}
Just like the arrow function, the arrow function component is a little cleaner than the function declaration. It looks nicer and more intuitive.
✨ Classes and the Extend keyword
As I said before, React has class components and functional components. The functional component is built with functions and the class components are built with classes.
Let's look at the example of the javascript class then we will look at react class components.
// javascript class
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
const square = new Rectangle(10, 10);
console.log(square.height); // output: "10"
Javascript classes are just templates for creating objects. with the new keyword, you can create a new object from the class. you can also use the extend keyword to create a new object from the class.
Example of Class component:
class App extends Component {
render() {
return (
<div>App</div>
)
}
}
Here we created a class component by extending the component class. it’s just the javascript class that returns HTML/JSX.
✨ Async/Await
Async-await is a very important javascript concept. but before we get into them you’ll first need to understand asynchronous javascript.
Asynchronous JavaScript
When building web apps you’ll need to make API calls to get data from the backend and these fetching operations might take a while to finish.
While fetching the data all the other functionalities would freeze. To prevent this javascript introduced asynchronous functions. That means asynchronous functions help you write code that will get the data from the API at the same time won’t block the rest of the application.
This is asynchronous javascript.
There are a few ways to handle asynchronous code, but I am going to talk about async/await. because it is currently the best way to handle async code.
Let’s start with an example:
async function getPersonsInfo(name) {
const people = await server.getPeople();
const person = people.find(person => { return person.name === name });
return person;
}
Async:
the async keyword declares that this function is an asynchronous function. an async function automatically returns a promise. an async keyword can be used in all types of functions. like, arrow function, callback function, or function expression.
Await:
What the await keyword does is it says an async function to wait to finish the operation. It is the same as the .then() block of a Promise. It’s just much cleaner.
One note here is that you can only use the await keyword inside an async function, otherwise you’ll get an error.
Handling Errors
As you can see the await keyword waits for the promise to resolve and returns the result. we need to keep in mind that our promise can be rejected. so, now we need a way to handle that.
We can handle errors in the async function in 2 ways.
Solution #1 - Use try ... catch()
blocks:
asyncFunctionCall().catch(error => {
console.error(error)
});
Solution #2 - Use Inner try ... catch()
block:
async function getPersonsInfo(name) {
try {
const people = await server.getPeople();
const person = people.find(person => { return person.name === name });
console.log(person)
} catch (error) {
console.error(error)
}
}
Async/await in React
const App = () => {
useEffect(() => {
// declare the data fetching function
const fetchData = async () => {
//get the data
const data = await fetch('<https://yourapi.com>');
}
// call the function
fetchData()
// make sure to catch any error
.catch(console.error);
}, [])
return <>...</>;
};
✨ Concept 5 - Array methods
Array methods are ways to manipulate arrays in javascript. Knowing how these methods work will come in handy in the future. Because when you start building projects with react you’ll use them all the time.
array.map()
array.map()
creates a new array by applying a callback function on each element of the array. also, it does not change the original array.
Code Sample
const numbers = [2, 3, 4, 6];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 2;
}
console.log(numbers); //2,3,4,6
console.log(newArr); //4,6,8,12
array.filter()
array.filter()
loop through all the elements of an array and filter out the elements that match the condition in the callback function. just like the map method, it doesn't change the old array.
Code Sample
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
console.log(ages);
console.log(result);
Example in React for
map()
function App() {
const names = ['sam', 'jack', 'tom', 'dave'];
return (
<div className='App'>
<h1>Hello world!</h1>
{
names.map(name => <h2>hello {name}</h2>)
}
</div>
);
}
The above sample renders all the elements of the names array using map
. This is very useful and probably you’ll use it all the time.
Example in React for
filter()
const numbers = [1, 2, 3, 4, 5, 6, 7];
const lessThanFive = numbers.filter(num => num < 5);
console.log(lessThanFive); //1,2,3,4
console.log(numbers) //1, 2, 3, 4, 5, 6, 7
Here I filtered the numbers array to less than five. This method is also very important for creating filter functionalities.
✨ Ternary Operator
Ternary Operator is the simplified form of the if/else conditional. Basically, It’s just another way to write if-else conditional.
Code Sample - Classic If/else
//if/else
if (loading) {
loadingComponent();
} else {
App();
}
Code Sample - Ternary Operator
loading ? loadingComponent() : App();
React Sample - Ternary Operator
class App extends Component {
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
}
✨ Template Literal
If you are building a web app, it’s normal that you need to work with strings. In earlier versions of Javascript (ES5), if you wanted to concatenate(add) a string to a variable you had to use the + operator. And it doesn’t look good and is not easy to understand.
But now you can use ES6 template literal. Template literal uses ${} notation to concatenate strings with variables.
Code Sample
const name = "Sam";
const greeting = `Hello, ${name}!`
console.log(greeting) // Hello, Sam!
✨ Destructuring
Destructuring is a way to extract values from an Object or Array into variables.
In earlier versions of Javascript (ES5), if you wanted to extract a value from an array or object you would do this:
//Array
const foo = ['one', 'two'];
const one = foo[0]
const bar = ["Tom", "Jerry"];
const tom = bar[0]
Now what you can do with ES6 (modern version of Javascript) restructuring is this:
const foo = ['one', 'two'];
const [one] = foo;
//Object
const bar = ["Tom", "Jerry"];
const {tom} = bar
It will assign the value one to the variable one. This is much cleaner and more intuitive.
Example In React.js
To pass data to components React uses props. Props are just like arguments in a normal function.
The point here is that props are objects. For example, if you had a component named Greeting
and it takes a prop name:
<Greeting name={"Sam"} />
If you want to access it, you need to write props.name.
function Greeting(props) {
return (
<div>hello {props.name}</div>
)
}
But also, you can use restructuring like this:
function Greeting(props) {
const {name} = props
return (
<div>hello {name}</div>
)
}
Now you can use the name without calling props.name
.
✨ Spread Operator
A spread operator is used to copy a whole or part of an array or an object.
The spread operator is used to create an exact copy of an Array or an Object. it is very handy when working with react states because states are immutable.
const arrayOne = [1, 2, 3];
const arrayTwo = [4, 5, 6];
const arrayThree = [...arrayOne, ...arrayTwo];
✨ Import and Export
As mentioned before, React is a component-based UI framework. So, to build a complete application you need to use the components you built.
To use the component you need to import them into the file you want to use. you can use export and import to use components in your application.
Export Sample
// app.js file - Exports the “App” object
function App() {
return (
<div>App</div>
)
}
Import Sample
// index.js - Use the “App” object via an “import”
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
After this short introduction of 10 useful JS concepts, we can use in React, curious minds might go further and code a simple Hello World
in React.
✨ Code Hello World
project with React
This section explains how to code a classic “Hello World” project using React and Javascript.
Step#1: Install the tools
To get started with React first you need to install Node.js. You can download Node from here.
Step#2: Build the app
After you’ve installed NodeJS, open up the terminal/command line and create your project folder with this command:
$ mkdir hello-react
Then generate a basic React project using CRA
(create-react-app tool).
$ npx create-react-app my-app
$ cd my-app
$ npm start
After running all these commands your browser will open up the React project on port 3000
.
import React from 'react'
function App() {
return (
<div></div>
)
}
export default App
And write an h1
tag with Hello world!
inside the div
.
import React from 'react'
function App() {
return (
<div>
<h1>hello world!</h1>
</div>
)
}
export default App
At this point, you should see Hello World
message in the browser.
Congrats! From now on
you are a React (beginner) developer
.
✨ Conclusion
You start learning/using React without understanding the Javascript basic concepts you might be unproductive and not use the full power of React.
Thanks for reading!
For more resources, feel free to access:
- ✨ More Free Dashboards crafted in Django, Flask, and React
- ✨ More Admin Dashboards - a huge index with products