You are on page 1of 36

React

Index

Introducti on Using ReactJS from CDN


Installation Using NPM Packages
React-app Setup FIRST PROJECT
Folder-Stutus State
ES6 PrPose
Function Components form
Class COMPONENTS Events in ReactJS
WHAT IS REACT.JS CSS
Features of ReactJS
Introduction-React is a JavaScript library
for building user interfaces

What Is React?
React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
It lets you compose complex UIs from small and isolated pieces of code called “components”.
React has a few different kinds of components, but we’ll start with React.Component

React (also known as React.js or ReactJS) is a free and open-source


front-end JavaScript library for creating UI component-based user
interfaces.
React is maintained by Meta (previously Facebook) along with a
community of individual developers and organizations.
How to Install React
The best way to install React or create a React project is to install it with create-react-app. This is one of the steps that
most beginners struggle with, but in this guide, we'll go over how to get started properly and successfully.
We'll be using our terminal for this (you can either make use of an in built terminal or download any you prefer). One
prerequisite is to have Node.js installed on your PC, knowing full well that NPM (or, alternatively, Yarn) is required. We'll be
using NPM for this guide.
To confirm that you have Node installed on your PC, just launch
your terminal/command prompt and type node -v and npm -v to see
which versions you have.Because create-react-app requires that
you have NPX installed,
you'll need to make sure your Node version is not less than v14.0.0 and your NPM version is not less than v5.6.
Suppose you have an older version of NPM,
you could use the following command to update it:
npm update-g
What is Create-react-app?

Though the name explains what it does, you might start to wonder
what create-react-app really means.
Creating a React app manually is complicated and time-consuming,
but create-react-app makes it much easier by automating all
the configuration and package installation.
create-react-app is the best way to start building
a new single-page application in React.
If you are interested in learning how to create a
React app manually without create-react-app,
you can check out this guide.
How to Create a React Application
The first step is to start your terminal/command prompt, navigate to the folder
where you want to save your React application, and then execute this command:
npx create-react-app my-app

Note: my-app is the name of the application


we are creating, but you can change it to any name of your choice.
The installation process may take a few minutes.
After it is done, you should see a folder that appears in
your workspace with the name you gave your app. Congratulations!
How to Run Your React Application
Now, head back to the terminal, and the first thing you need to do is
navigate to the directory where the app was installed using cd my-app.
Then finally run npm start to see your app live on localhost:3000.
You should see something like this:
Directory Structure
We've just finished the first part of this article. Now let's figure out what each file and folder in our
React application means and does. This is critical either as a beginner or an experienced React
developer.
The directory structure of your newly created React app looks like this when you open it:
Let’s now start by explaining these folders and what they stand for:
node_modules folder
The node_modules folder contains all of our dependencies, and this folder is ignored when we set up source
control.
But it is important to note that the package.json file works in tandem with the node_modules folder because
it contains information about all of the dependencies as well as some script commands.
If you delete the node_modules folder, the application will break because you'll no longer have your
dependencies.
To re-install these dependencies, you can use npm install – this will check the pakage.json file for a list of
the dependencies and then install all of them. This will make it easy for you to push
your code online or share your code with others without having to share the heavy node_modules folder.
Note: This is not just for create-react-app.

public folder
Although the majority of the work will be done in the src folder, the public folder contai
static files, such as the HTML file. You could, for example, change the title of your web
add CDNs such as Google Fonts, and so on.
Note: Don't be afraid of this file because
it's just a regular HTML file. The only code to remember is
the div with the id root where the entire React application will be placed.
<div id="root"></div>
.gitignore file
Just as the name suggests, it’s a file that specifies which files and folders will be ignored by our source control.
When you open the file, you will see a list of files that are being ignored, including the node_modules and build folder.
You can decide to add some particular files or folders.
build folder
The build folder is another folder that you can't see right now, but that you'll see when you build your project.
This will create a production-ready folder of static assets that can be hosted or deployed using a drag-and-drop option on a platform like Netlif
src folder
So far, we've covered some fundamental folders, but our main concern is the src folder, which is where development takes place.
Here's what the src folder looks like:
                                      
Let's start with the fundamental files: App.js, index.js, index.css, and App.css (you can delete every other file for now).
App.js
This is where all of your components will eventually meet. The name of the file isn't important,
but it's good practice to keep this name so that other developers can understand your code.
index.js
This is the starting point for your application. More specifically, this is where you target the root id from
the index.html file and render the App.js file, which is where your entire file (components and pages) will meet.

import React from 'react';


import ReactDOM from 'react-dom';
import App from './App'; ReactDOM.
render( <React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
App.css and index.css
These both contain styles for your application.
The index.css file contains global styling and the App.css file almost works the same as it does for
the App.js file – but whether we use a CSS file is entirely up to us. While getting started,
we can choose to delete one and use only one CSS file.
Understanding JSX
JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together.
Writing code in React takes a long time because you have to use
the React.createElement function every time, even if you are just adding a simple div.
The image above depicts the exact same code written in JSX and with React.createElement. You can tell which is easier
to write, understand, and manage by comparing the two.
create-react-app internally uses Babel for the JSX to JavaScript conversion, so you don't have to worry about configuring your own babel configuration
with Webpack.
Some Do’s and Don’t of JSX
Make sure you're aware of some of these important details so that some bugs don't get in your way:
•Your markup is usually placed after the return statement, either as a single line of code or as a block code.
•All of your code should be wrapped in a single tag. This could be a div, a tag with no content (<>), or any other tag.
const App = () => { return ( <h1>JSX Title</h1> <p>This is first JSX Element!</p> <p>This is another JSX Element</p> ); };
This works fine with normal markup but would result in a major error because React requires adjacent elements to be wrapped in a parent tag.
This simply means that for this code to run, it must be wrapped in a parent tag, such as a div, section, article, and so on.
const App = () => { return ( <div> <h1>JSX Title</h1>

const App = () => {


return (
<div>
<h1>JSX Title</h1>
<p>This is first JSX Element!</p>
<p>This is another JSX Element</p>
</div>
); };
You can also make use of the React.Fragment component.
What is ES6?
ES6 stands for ECMAScript 6.
ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of ECMAScript, it was published in
2015, and is also known as ECMAScript 2015.

Why Should I Learn ES6?


React uses ES6, and you should be familiar with some of the new features like:
•Classes
•Arrow Functions
•Variables (let, const, var)
•Array Methods like .map()
•Destructuring
•Modules
•Ternary Operator
•Spread Operator
Classes
ES6 introduced classes.
A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside
a constructor() method.

Example

class Car {
constructor(name)
{ this.brand = name;
}
}
Functional Components: Functional components are some of the more common components that will come across while
working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript
Syntax:
function.
const Car=()=> { return <h2>Hi, I am also a Car!</h2>; }

Example-
import React, { useState } from "react";

 
const FunctionalComponent=()=>{
    const [count, setCount] = useState(0);

 
    const increase = () => {
        setCount(count+1);
    }

 
    return (
        <div style={{margin:'50px'}}>
            <h1>Welcome to Geeks for Geeks </h1>
            <h3>Counter App using Functional Component : </h3>
          <h2>{count}</h2>
            <button onClick={increase}>Add</button>
        </div>
    )

 
 
Class Component: This is the bread and butter of most modern web apps built in ReactJS. These components are simple classes
(made up of multiple functions that add functionality to the application).

Syntax-
class car extends React.COMPONENTS {
render({
return import React, { Component } from "react";
<h2>HI I AM A CAR</h2>);
}}  
class ClassComponent extends React.Component{
    constructor(){
        super();
        this.state={
            count :0
        };
        this.increase=this.increase.bind(this);
    }
     
   increase(){
       this.setState({count : this.state.count +1});
   }
 
    render(){
        return (
            <div style={{margin:'50px'}}>
               <h1>Welcome to Geeks for Geeks </h1>
               <h3>Counter App using Class Component : </h3>
               <h2> {this.state.count}</h2> 
               <button onClick={this.increase}> Add</button>
 
            </div>
        )
    }
}
                         Functional Components                                            Class Components                

A functional component is just a plain JavaScript pure function that A class component requires you to extend from React. Component
accepts props as an argument and returns a React element(JSX). and create a render function which returns a React element.

It must have the render() method returning JSX (which is


There is no render method used in functional components.
syntactically similar to HTML)

Class component is instantiated and different life cycle method is


Functional component run from top to bottom and once the
kept alive and being run and invoked depending on phase of class
function is returned it cant be kept alive.
component.

Also known as Stateless components as they simply accept data and


Also known as Stateful components because they implement logic
display them in some form, that they are mainly responsible for and state.
rendering UI.

React lifecycle methods (for example, componentDidMount) cannot React lifecycle methods can be used inside class components (for
be used in functional components. example, componentDidMount).

It requires different syntax inside a class component to implement


hooks.
Hooks can be easily used in functional components to make them
example: constructor(props) {
Stateful.
   super(props);
example: const [name,SetName]= React.useState(‘ ‘)
   this.state = {name: ‘ ‘}
}

Constructors are not used. Constructor are used as it needs to store state. 
interfaces. ReactJS is maintained by Facebook and a community of individual
developers and companies. It is widely used as a base in building single-page
websites and mobile applications. It is very easy to use, and it allows users to create
reusable UI components.
In this ReactJS Tutorial for beginners, you will learn ReactJS step by step:
Features of ReactJS
JSX : JSX is an extension to javascript. Though it is not mandatory to use JSX in react, it is one of the good
features and easy to use.
Components: Components are like pure javascript functions that help make the code easy by splitting the
logic into reusable independent code. We can use components as functions and components as classes.
Components also have a state, props which makes life easy. Inside a class, the state of each of the props is
maintained.
Virtual DOM: React creates a virtual dom, i.e., in-memory data -structure cache. Only the final changes of
DOM has later updated in the browsers DOM.
Javascript Expressions: JS expressions can be used in the jsx files using curly brackets, for example {}.
Advantages of ReactJS
Here, are important pros/benefits of using ReactJS:
ReactJS uses virtual dom that makes use of in-memory data-structure cache, and only the final changes are updated in browsers dom. This
makes the app faster.
You can create components of your choice by using the react component feature. The components can be reused and also helpful in code
maintenance.
Reactjs is an open-source javascript library, so it is easy to start with.
ReactJS has become very popular in a short span and maintained by Facebook and Instagram. It is used by many famous companies like Apple,
Netflix, etc.
Facebook maintains ReactJS, the library, so it is well maintained and kept updated.
ReactJS can be used to develop rich UI for both desktop and mobile apps.
Easy to debug and test as most of the coding is done in Javascript rather than on Html.
Disadvantages of ReactJS
Here, are cons/ drawbacks of using ReactJS:
Most of the code is written in JSX, i.e., Html and css are part of javascript, it can be quite confusing as most other frameworks prefer keeping
Html separate from the javascript code.
The file size of ReactJS is large.
Using ReactJS from CDN
To start working with react, we need to first install reactjs. You can easily get started to use reactjs by using the CDN javascript files, as shown below.
Go to the official site of reactjs to get the CDN links, i.e., https://reactjs.org/docs/cdn-links.html and you will get the required files to explain the following image.
Using NPM Packages
Make sure you have nodejs installed. If not installed, go through this tutorial for nodejs (https://www.guru99.com/node-js-tutorial.html) installation.
Once you have nodejs installed, create a folder reactproj/.
To start with project setup, run command npm init.
This is how the folder structure will look like:
reactproj\ package.json
Now we will install the packages that we need.
Here are the list of packages for reactjs:
npm install react --save-dev npm install react-dom --save-dev npm install react-scripts --save-dev
Open the command prompt and run above commands inside the folder reactproj/.
Create a folder src/ where all the js code will come in that folder. All the code for reactjs project will be available in the src/ folder. Create a file index.js and add import react and react-dom, a
index.js

index.js
import React from 'react';
import ReactDOM from 'react-dom'; ReactDOM.
render(
<h1>Hello, from Guru99 Tutorials!</h1>,
document.getElementById('root')

);
The package react-scripts will take care of compiling the code and starting the server to display the html file i.e
index.html. You need to add the command in package.json that will take care of using react-scripts to compile
the code and start server as shown below:
"scripts": { "start": "react-scripts start" }

After installing all the packages and adding the above command, the final package.json is as follows:
Package.json
{

"name": "reactproj",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": { "start":
"react-scripts start"

},
"author": "",
"license": "ISC",
"devDependencies": { "react": "^16.9.0",
"react-dom": “
^16.9.0", "react-scripts": "^3.1.1“
}}

To start testing reactjs run the command


npm run start

C:\reactproj>npm run start > reactproj@1.0.0 start


C:\reactproj > react-scripts start
How to Create Your First React Project Setup
Here is a step by step guide in this ReactJS Tutorial to start with the first react application.
Step 1) Import the react packages.
1. To start with ReactJS, we need to first import the react packages as follows.
import React from 'react'; import ReactDOM from 'react-dom';
2. Save the file as index.js in src/ folder
Step 2) Write Simple Code.
We will write a simple code in this tutorial React JS, wherein we will display the message “Hello, from Guru99 Tutorials!”
ReactDOM.render( <h1>Hello, from Guru99 Tutorials!</h1>, document.getElementById('root') );

ReactDOM.render will add the <h1> tag to the element with id root. Here is the html file we are having:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>ReactJS Demo</title>
</head> <body>
<div id = "root">
</div>
</body>
</html>
Step 3) Compile the Code.
Next in this React.js Tutorial, we need to compile the code to get the output in the browser.
Here is the folder structure:
reactproj/
node_modules/
src/ index.js
package.json public/
index.html
import React from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component {
constructor(props)
{ super(props);
this.state = { msg: "Hello, from Guru99 Tutorials!" } }
render(
) { return
<h1>{this.state.msg}</h1>; }
} export default Hello;
index.js

import React from 'react';


import ReactDOM from 'react-dom';
import Hello from './test.jsx';
ReactDOM.rende
r(
<Hello />,
document.getElementById('root')
);
This is what we get when we test it in the browser:
What are Props in ReactJS?
Props are properties to be used inside a component. They act as global object or variables which can be used inside the Component.
Props to Function Component
Here is an example of passing props to a function component.

import React from 'react';


import ReactDOM from 'react-dom‘
; function Hello(props) {
return
<h1>{props.msg}</h1>;
} const Hello_comp = <Hello msg="Hello, from Tutorials!" />;
index.jsexport default Hello_comp;
import React from 'react';
import ReactDOM from 'react-dom';
import Hello_comp from './test.jsx';
ReactDOM.render(
Hello_comp, document.getElementById('root')
);
Update: In this state, the dom is interacted by a user and updated. For example, you enter something in the textbox, so the state properties are updated.
Following are the methods available in update state:
shouldComponentUpdate() : called when the component is updated.
componentDidUpdate() : after the component is updated.
UnMounting: this state comes into the picture when the Component is not required or removed.
Following are the methods available in unmount state:
Component willUnmount(): called when the Component is removed or destroyed.
Working Example
Here is a working example which shows the methods called at each state.
Example: complife.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class COMP_LIFE extends React.Component {
constructor(props) {
super(props); this.state = {name: ''}; this.UpdateName = this.UpdateName.bind(this); this.testclick = this.testclick.bind(this); } UpdateName(event) { this.setState({name: event.target.value}); } testclick(event) { al
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import COMP_LIFE from './complife.jsx'; ReactDOM.render( <COMP_LIFE />, document.getElementById('root') );
When you check the output in the browser
Working with Forms
In reactjs Html input elements like <input />, <textarea /> and <select /> has their own state and needs to be updated when user
interacts using the setState() method.
In this chapter, we will see how to work with forms in reactjs.

form.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class Form extends React.Component {
constructor(props) { super(props); this.state = {name: ''}; this.UpdateName = this.UpdateName.bind(this); this.formSubmit = this.formSubmit.bind(this); } UpdateName(event) { this.setState({name: event.target.value});
For the input fields, we need to maintain the state, so for that react provides a special method called setState, which helps to maintain the state whenever there is a c
We have used events onChange and onClick on the textbox and submit button. When the user enters inside the textbox the onChange event is called, and the name fi
UpdateName(event) { this.setState({name: event.target.value}); }
Working with Events in ReactJS
Working with events in reactjs is same as how you would have done in javascript. You can use all the event handlers that are used
in javascript. The setState() method is used to update the state when the user interacts with any Html element.
Here is a working example of how to use events in reactjs.

events.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class EventTest extends React.Component {
constructor(props) {
super(props);
this.state = {name: ''};
this.UpdateName = this.UpdateName.bind(this);
this.testclick = this.testclick.bind(this);
}
UpdateName(event) { this.setState({name: event.target.value}
); } testclick(event) { alert("The name entered is: "+ this.state.name
); } render() {
return (
<div> Enter Your Name:
<input type="text" value={this.state.name} onChange={this.UpdateName} />
<br/> <h2>{this.state.name}</h2>
<input type="button" value="Click Here" onClick={this.testclick} />
</div>
);
}
} export default EventTest;
We have used events onChange and onClick on the textbox and button. When the user enters inside the textbox the onChange event is
UpdateName(event) { this.setState({name: event.target.value}); }
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import EventTest from './events.jsx';
ReactDOM.
render( <EventTest />, document.getElementById('root')
);
Here is the output in the browser:
Working with Inline CSS in ReactJS
Will take a look at a working example to understand the working of inline css in reactjs.
addstyle.jsx
import React from 'react';
import ReactDOM from 'react-dom';
const h1Style = { color: 'red' }; function Hello(props)
{
return
<h1 style={h1Style}>{props.msg}</h1>;
}
const Hello_comp = <Hello msg="Hello, from Guru99 Tutorials!" />;
export default Hello_comp;

I have added color: ‘red’ style to the h1 tag.


index.js
import React from 'react‘
; import ReactDOM from 'react-dom';
import Hello_comp from './addstyle.jsx';
ReactDOM.render( Hello_comp, document.getElementById('root')
);
Working with External CSS in ReactJS
Let us create a external css , for that create a folder css/ and add style.css in it.
style.css
.h1tag { color:red; }

addstyle.jsx
import React from 'react';
import ReactDOM from 'react-dom';
let classforh1 = 'h1tag'; function Hello(props) {
return
<h1 className={classforh1}>{props.msg}</h1>;
} const Hello_comp = <Hello msg="Hello,
from Guru99 Tutorials!" />;
export default Hello_comp;

You might also like