React Basic
React Basic
React –I Module
Index
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
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
public folder
Although the majority of the work will be done in the src folder, the public folder contains some
static files, such as the HTML file. You could, for example, change the title of your web app,
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.
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 function.
Syntax:
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>
)
}
Syntax-
class car extends React.COMPONENTS {
render({
return
<h2>HI I AM A CAR</h2>);
}}
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.
React lifecycle methods (for example, componentDidMount) cannot React lifecycle methods can be used inside class components (for
be used in functional components. example, componentDidMount).
Constructors are not used. Constructor are used as it needs to store state.
What is ReactJS?
ReactJS is an open-source front-end JavaScript library for building
user 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 reac
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“
}}
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
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
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;
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;