React is free, open-source & component-based front end library which is responsible for the frontend of the application. It is developed and maintained by Facebook.
React was the most popular JavaScript library in 2021.
React is flexible, easy to learn & has a great community support.
If you want to learn the framework that will give you the best odds of landing a job in 2022, your best bet is still React.
Prerequisites
In this blog
- Essential React Concepts (creating react app, Components, JSX, Props, State, Hooks)
- Counter Application
- How to fetch data from an API in React
Setup & Installation
Open your favorite text editor & let's get started.
(I will be using Visual Studio Code)
Open your command prompt (windows) or terminal (Mac).
Make sure you have installed Node JS (npx comes with Node JS)
In your terminal:
npx create-react-app react-basic-concepts
This will create a new react app with name react-basic-concepts
You can see React app is installed in my ADMIN folder.
Now, let's run our application. In your terminal
cd react-basic-conecpts
npm start
This will run our app on localhost:3000
Now open react-basic-concepts folder in your text editor
Let's understand the project structure, you'll see a /public and /src directory with the regular node_modules (conatins all dependencies), .gitignore, README.md, and package.json.
In /public, our important file is index.html
The /src directory will contain all our React code.
Let's do some cleanup & remove unnecessary files.
In src directory keep these files & delete rest of them.
Your index.js file should look like this
Delete everything from App.js
Open App.js file & let's create our first component.
import React from "react"; // importing React
const App = () => { // creating App component
return (
<div> // JSX (we'll look into this later)
<h1>Hello, world!</h1>
</div>
);
};
export default App; // exporting App
Save your file & go to your browser, you'll see Hello, world!
Congratulations on creating your first React Component!
Basic Concepts
Components
React components let you break up the UI into separate pieces that can then be reused in your entire project.
Components are independent & reusable pieces of code.
There are two ways of creating a component in React
- Function Components
A React functional components is nothing but a regular JavaScript function that returns JSX.
import React from "react";
const App = () => { component
return (
<div>
<h1>Hello, world!</h1>
</div>
);
};
export default App;
- Class Components
A class component is JavaScript class with render method.
export default class HelloMessage extends React.Component {
render() {
return (
<div>
Hello, world!
</div>
);
}
}
Functional components are short, simple, easy to read & maintain.
However, the rendering time and performance in either components do not make a lot of differences.
Note: Always start component names with a capital letter.
JSX: JavaScript + XML
Instead of putting JavaScript into HTML,
JSX allows us to put HTML into JavaScript.
Take a look at the below code:
const jsx = <h1>This is JSX</h1>
JSX stands for JavaScript XML.
It is simply a syntax extension of React.
It allows us to directly write HTML in React.
To add JavaScript inside JSX, we need to write it in curly brackets:
const App = () => {
const name = "Pratham";
return (
<div className="App">
<p>Hello, {name}</p>
</div>
);
};
Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
For example, class becomes className in JSX, and tabindex becomes tabIndex.
Props
Props is short for properties and they are used to pass data between React components.
To use props, you have to pass props as argument in our JS function.
Take a look at example below:
/src/App.js
import React from "react";
import Names from "./Components/Names";
const App = () => {
return (
<div>
<Names name="Pratham" />
<Names name="Pratik" />
<Names name="Saif" />
</div>
);
};
export default App;
Create new folder in /src & name it components, then create Name.js file in /src/components
/src/Components/Names.js
import React from "react";
const Names = (props) => {
return (
<div>
<h1>Hello, {props.name}</h1>
</div>
);
};
export default Names;
Open localhost:3000 you should see:
Hooks
Hooks allow us to add state to add state to functional components and to share logic across components.
(Note: Hooks can only be used inside function components.)
React have few built-in hooks like useEffect, useState, etc. You can also create your own custom hooks in React.
Let's take a look at useState hook by creating a counter application
Basic Counter application
Create new component in /src/Components
import React, { useState } from 'react';
function Counter() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
count stores the initial value & setCount is used to update that value.
Here, the initial value of the count is 0, then setCount function is used to update the value of count.
Render Counter in App.js & open localhost:3000 in your browser
import React from "react";
import Counter from "./Components/Counter";
const App = () => {
return (
<div>
<Counter />
</div>
);
};
export default App;
You can learn more about React hooks here.
Working with API in React
To fetch data from an API in react we will be using useEffect hook.
To understand the useEffect hook you first need to understand lifecycle of the component. The lifecycle of the component contains three main parts i.e. mounting, updating and unmounting.
mounting: when the page loads
updating: when the state updates
unmounting: when user leaves the page
In this case, we will fetch our data:
useEffect(() => {
// data fetching here
}, []);
The above code will fetch data when component mouts, that means, on the first render when the page loads.
Let's fetch data from books API.
// + add the useEffect import
import { useState, useEffect } from "react";
function App() {
const [books, setBooks] = useState(null);
// + adding the use
useEffect(() => {
getData();
// we will use async/await to fetch this data
async function getData() {
const response = await fetch(
"https://www.anapioficeandfire.com/api/books"
);
const data = await response.json();
// store the data into our books variable
setBooks(data);
}
}, []);
return (
<div>
<h1>Game of Thrones Books</h1>
{/* display books from the API */}
{books && (
<div className="books">
{/* loop over the books */}
{books.map((book, index) => (
<div key={index}>
<h2>{book.name}</h2>
</div>
))}
</div>
)}
</div>
);
}
export default App;
Now open localhost:3000 & see the magic
Some resources to learn React
Practical React series by Ben awad
That was hell lot of a knowledge.
I'm proud of you if you've managed to make it till here.
IF YOU ENJOYED THIS, THEN YOU CAN BUY ME MY FIRST COFFEE EVER, THANK YOU
Happy coding!
Top comments (0)