React JS- Basics
React is Java Script Library used For Building user interfaces. React is used for Building Single page applications. React allows us to create reusable UI components. This blog is intended to explain the basics of Reactjs.
Prerequisite:
Before learning Reactjs in-depth, you must have a good knowledge of Javascript,
HTML5, and CSS. The knowledge of Ecmascript 2015 syntax can also be helpful.
History of react:
It was first created and used by facebook in 2011 for newsfeed feature.
Facebook engineer Jordan Walke created it.
First public release of react in 2013 july.
Introduction to React:
Today, most of the websites are built using MVC (model view controller)
architecture. In MVC architecture, React is the 'V' which stands for view.
A reactjs application is made up of multiple components, each component
responsible for outputting a small, reusable piece of HTML code. The components
are the heart of all React applications. These Components can be nested with
other components to allow complex applications to be built of simple building
blocks. Reactjs uses virtual DOM based mechanism to fill data in HTML DOM. The
virtual DOM works fast as it only changes individual DOM elements instead of
reloading complete DOM every time.
To create React app, we write React components that correspond to
various elements. We organize these components inside higher level components
which define the application structure.
How React
works:
I am starting this blog by explaining why Reactjs is preferred more for
front end development .
1.The main objective of developers is to develop user interface (UI)
that improves the speed of the application.
React Uses Virtual DOM:
Instead of manipulating the browsers Dom Dom directly react creates
virtual Dom in the memory .where it does the all necessary manipulating before
making changes in the Browsers Dom.
React only changes what need to be changed:
React Finds out what changes have been made and changes only what needs
to be changed.
Why learn react:
Today, many javascript frameworks are available in the market(like
angular, node), but still, React came into the market and gained popularity
amongst them. The previous frameworks follow the traditional data flow
structure, which uses the DOM (Document Object Model). DOM is an object which
is created by the browser each time a web page is loaded. It dynamically adds
or removes the data at the back end and when any modifications were done, then
each time a new DOM is created for the same page. This repeated creation of DOM
makes unnecessary memory wastage and reduces the performance of the
application.
Therefore, a new technology reactjs framework invented which remove this
drawback. Reactjs allows you to divide your entire application into various
components. Reactjs still used the same traditional data flow, but it is not
directly operating on the browser's Document Object Model (DOM) immediately;
instead, it operates on a virtual DOM. It means rather than manipulating the
document in a browser after changes to our data, it resolves changes on a DOM
built and run entirely in memory. After the virtual DOM has been updated, React
determines what changes made to the actual browser's DOM. The React Virtual DOM
exists entirely in memory and is a representation of the web browser's DOM. Due
to this, when we write a React component, we did not write directly to the DOM;
instead, we are writing virtual components that react will turn into the DOM.
Features of React.js: There are unique features are available on React
because that it is widely popular.
·
Use JSX: It
is faster than normal javascript as it performs optimizations while translating
to regular javascript. It makes it easier for us to create templates.
·
Virtual DOM: Virtual
DOM exists which is like a lightweight copy of the actual DOM. So for every
object that exists in the original DOM, there is an object for that in React
Virtual DOM. It is exactly the same, but it does not have the power to directly
change the layout of the document. Manipulating DOM is slow, but manipulating
Virtual DOM is fast as nothing gets drawn on the screen.
·
One-way Data Binding: This
feature gives you better control over your application.
·
Component: A
Component is one of the core building blocks of React. In other words, we can
say that every application you will develop in React will be made up of pieces
called components. Components make the task of building uis much easier. You
can see a UI broken down into multiple individual pieces called components and
work on them independently and merge them all in a parent component which will
be your final UI.
·
Performance: React.js
use JSX, which is faster compared to normal javascript and HTML. Virtual DOM is
a less time taking procedure to update webpages content
Lets Start Learning React:
Installing Setup:
In this section, we will learn how to set up an environment for the
successful development of reactjs application.
Pre-requisite for reactjs
Nodejs and NPM
React and React DOM
Webpack
Babel.
Ways to install Reactjs:
1. Using npm method
2. Using Create-react-app
In npm method You need install everything separately it is more
timetaking and hard to understand.
Create-react-app method:
The 'create-react-app' is a tool maintained by Facebook itself. This is
suitable for beginners without manually having to deal with tools like webpack
and babel.
Installing nodejs:
Nodejs and NPM are the platforms need to develop any reactjs
application. You can install nodejs and NPM package manager by navigating to
nodejs.org on your browser.
Then select your respective Operating system and
processor type .and choose latest version of nodejs.
After installing use the below commands to check that
if Nodejs and npm are installed properly or not.
node –v
npm –v.
Installing React:
After installing the nodejs You can install React by
using the below command on the terminal,
npm install –g create-react-app
Creating the project:
After installing the React you can create your project
using the below command,
create-react-app
project_name
You can use the below command which will do both
installing react and creating the project.
npx create-react-app
project_name.
This will create a project with the following folders.
Running your Project:
After creating the Project you can run your project by
using the following Command. First you need to navigate to the project folder
using terminal then using the below command you can run your project.
npm start
This command will Run your project on your Browser
local host.
Folder Structure:
1.Package.Json:
This file contains all the dependencies to React.
2.Node Modules:
It is the folder where All the Dependencies were installed. It is generated while
Installing Create App command.
3.Public Folder:
Manifestjson: Concerned with progressive web apps.
Index.HTML: only html file in the folder , it is the
main part for creating single page web applications. we are not going to change
anything in this file.
4.Src Folder:
This is the Folder you will be working with more During
the development.
Index.js: This is the js File where App components is
imported and rendered to the root.
App.js : This is a file contains code for the component
,you can create multiple component files .
Css files: it is file contains Code for styling the
components.
React Components:
1.
A Component is one of the core building blocks of
React. In other words, we can say that every application you will develop in
React will be made up of pieces called components. Components make the task of
building is much easier.
2. Components are like functions that
return HTML elements.
3. Components are reusable and can be nested inside another
component .It is Part(header, footer ,body)of user interface.
4. Components are stored in Js files ,
components are the code inside js files.
React Components
Components are independent and reusable bits
of code. They serve the same purpose as javascript functions, but work in
isolation and return HTML.
Components come in two types, Class
components and Function components.
Create Your First
Component
When creating a React component, the
component's name MUST start with an upper case letter.
Class Component:
A class component must include the extends
React.Component statement. This statement creates an
inheritance to React.Component, and gives your component access to
React.Component's functions.
The component also requires a render() method, this
method returns HTML.
Example:
class Demo extends
React.Component {
render() {
return <h2>welcome to
react!</h2>;
}
}
Function Component
A Function component also returns HTML, and
behaves much the same way as a Class component, but Function components can be
written using much less code, are easier to understand.
Example:
function Demo1() {
return <h2>Lets start learning!</h2>;
}
Now your React application has a component called Demo,
which returns an <h2> element.
Example:
const root = reactdom.createroot(document.getelementbyid('root'));
root.render(<div>
<Demo />
<Demo1>
</div>);
This Component Will Return the component in
the browser.
React Props:
Components can be passed as props
,
which stands for properties.
Props are like function arguments, and you
send them into the component as attributes.
Props in class
component:
In Class Component using this.props.attribute in the render function you can pass argument/ input to
the component
class Demo extends
React.Component {
render() {
Return <h2>welcome to {this.props.company}!</h2>;
}
}
Use an attribute to pass a argument to the
component, and use it in the render() function:
function Demo1(props)
{
return <h2>let’s start learning {props.course} !</h2>;
}
While rendering the component you have to
pass the attribute value ,
const root = reactdom.createroot(document.getelementbyid('root'));
root.render(<div>
<Demo
company="mayura"/>
<Demo1
course="react"/>
</div>);
Components in
Components
We can refer to components inside other
components. React allows us to nesting a component inside another component.
This will also return the same output like the previous one.
Components in
Files
React is all about re-using code, and it is
recommended to split your components into separate files. You can create
different components in different files using export and import you can use the
component inside your application like,
Step:1 creating a component
in a separate js file and export the component.
import React from 'react';
class Demo extends
React.Component {
render() {
return <h2>welcome to
{this.props.company}!</h2>;
}}
export default Demo
Step 2 :importing the
component and nesting the component inside the new component and rendering the
new component inside root.
import React from
'react';
import reactdom from
'react-dom/client';
import Demo from
'./components/class_component';
import Demo1 from
'./components/function_component';
function App()
{return(
<div>
<Demo company='Kosar' />
<Demo1 course="react"/>
</div>
);
}
const root = reactdom.createroot(document.getelementbyid('root'));
root.render(<App
/> );
This will return,
React states:
The state is an updatable structure that is used to
contain data or information about the component. The state in a component can
change over time. The change in state over time can happen as a response to
user action or system event.React class
components have built in states. State of a component is an object that holds
some information that may change over the lifetime of the component.
Creating
a state:
1.To define a state you have to set
a default set of values to define the component initial state.
2. Add a constructor that defines
the initial state using the command (this .state)
3.the state property can be
rendered by render method={this .state. Property}
If you want to change the state
value we use the command (this. Setstate )when the value in the state object so
the component will re render so the output will be changed accordingly.
Step:1
setting the initial state:
class
Login extends React.Component{
constructor(){
super();
this.state={message1:'are you a new
user ',
meassage2:'create an
Account',
button:'create'}
}
}
2.Using
the state:
class
Login extends React.Component{
constructor(){
super();
this.state={message1:'are you a new
user ',
meassage2:'create an
Account',
button:'create'}
}
}
render(){
return(
<div>
<h2>{this.state.message1}</h2>
<h3>{this.state.message2}</h3>
<button>{this.state.button}</button>
</div>
);
}
3.Updating
the state:
import
react from "react";
class
Login extends react.component{
constructor(){
super();
this.state={message1:'are you a new
user ',
message2:'create an
account',
button:'create'}
}
update_login=()=>{
this.setstate(
{message1:'your account is created ',
message2:'please login',
button:'login'}
);
}
render()
{return(
<div>
<h2>{this.state.message1}</h2>
<h3>{this.state.message2}</h3>
<button type='button'
onclick={this.update_login}>{this.state.button}</button>
</div>
);
}
}
export
default Login
Output:
1.using
the state:
2.Updating
the state:
When you click the button the
values have change by the use of react states.
Props Vs
State:
Props |
State |
Props are read-only. |
State changes can be
asynchronous. |
Props
are immutable. |
State
is mutable. |
Props allow you to pass
data from one component to other components as an argument. |
State holds information
about the components. |
Props can be accessed by the child
component. |
State
cannot be accessed by child components. |
Props are used to
communicate between components. |
States can be used for
rendering dynamic changes with the component |
React Events:
An event is an action that could be triggered as a
result of the user action or system generated event. For example, a mouse
click, loading of a web page, pressing a key, window resizes, and other
interactions are called events.
Just like HTML DOM events, React can
perform actions based on user events.React has the same events as HTML: click,
change, mouseover etc.
Adding Events
React events are written in camelcase syntax:
Onclick instead of onclick.
React event handlers are written inside curly braces:
Onclick={shoot} instead of onclick="shoot()".
Example:
function event() {
const click = () => {
alert("you are entered the page");
}
return (
<button onclick={click}>Enter</button>
);
}
Passing
Arguments to the Events:
Example:
function event(a) {
const click = (a) => {
alert("a");
}
return (
<button onclick={()=>click(‘you are entered into
page’}>Enter</button>
);
}
This will return the same as
previous result.
React conditionals:
In React, conditional rendering refers to the process
of delivering elements and components based on certain conditions.
There are several ways to do
Conditional Rendering in react.
1.If
statement:
In If statement first we create two
components, then create another component that chooses which component to render
based on the condition.
Example:
creating Components:
function
Madelogout() {
return <h1>loggedout!</h1>;
}
function
Madelogin() {
return <h1>logged in!</h1>;
}
Example:
Rendering the component inside another based on the condition.
function
Login(props) {
const isLogin = props.login;
If (isLogin) {
return <Madelogin/>;
}
return <Madelogout/>;
}
export
default Login.
Then passing the condition value
while rendering in the app component.
<Login islogin={false}/>
Based on the Condition Value this
will return the respective Component.
2.Ternary
operater:
In this method we define the
components first then create a component and use ternary operator to pass a condition
and based on the condition value it will render the respective component.
Ternary
operator= Condition? True: false
Example:
function
Login(props) {
const islogin = props.islogin;
return (
<div>
{ islogin ? <Madelogin/> : <Madelogout/>
}
<div/>
);
}
export
default Login.
Then passing the condition value
while rendering in the app component.
<Login islogin={true}/>
Based on the Condition Value this
will return the respective Component
React
Lists:
Lists are used to display data in an ordered format and
mainly used to display menus on websites. In React, Lists can be created in a
similar way as we create lists in javascript.
The map() function is used for traversing the lists.
Example:
function
Navmenu(props)
{
const list = [1,2,3,4,5];
const updatedlist = list.map((listitems)=>{
return(
<li>
{listitems}
</li>
);
});
return(
<ul>{updatedlist }</ul>
);
}
React
Keys:
Keys allow React to keep track of elements.
This way, if an item is updated or removed, only that item will be re-rendered
instead of the entire list.
Keys need to be unique to each sibling. But
they can be duplicated globally.
Example:
function
Navmenu(props)
{
const list = [{id: 1, name:
'bread',dept:'food'},
{id: 2, name: 'milk',dept:'food'},
{id: 3, name: 'eggs',dept:'food'}];
const updatedlist = list.map((listitems)=>{
return(
<li key={listitems.id}>
{listitems.name}
</li>
);
});
return(
<ul>{updatedlist }</ul>
);
}
It will return a list shows the
name only. Using key you can render the data you wanted. If your list don’t
have a unique id you can use tostring ()
as a key
React
Forms:
Jus t like Html react allows users
to interact with the webpage.In react adding Forms is same as Html.
Example:
function
myform() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
This will return,
This will work as normal, the form will submit
and the page will refresh.But this is generally not what we want to happen in
React.We want to prevent this default behaviour and let React control the form.
Handling Forms
Handling forms is about how you handle the
data when it changes value or gets submitted. In HTML, form data is usually
handled by the DOM. In React, form data is usually handled by the components. When
the data is handled by the components, all the data is stored in the component
state.
You can control changes by adding event
handlers in the onchange
attribute.
Example:
import
React from "react"
class
Form extends React.Component {
constructor(props) {
super(props)
this.state = {
Username:
'',
Password:
'',
}
}
handleusernamechange = event => {
This.setstate({
Username:
event.target.value
})
}
handlepasswordchange = event => {
This.setstate({
Password:
event.target.value
})
}
render()
{
Const { username,
password } = this.state
Return (
<form>
<div>
<label>Username
</label>
<input
Type="text"
Value={username}
Onchange={this.handleusernamechange}
/>
</div>
<div>
<label>Comments</label>
<textarea
Value={password}
Onchange={this.handlepasswordchange}
/>
</div>
<button
type="submit">Submit</button>
</form>
)
}
}
export
default Form
Submitting Forms:
You can control the submit action by adding
an event handler in the onsubmit attribute for the <form>:
This will return,
React
Route:
React Router is a standard library for
routing in React. It enables the navigation among views of various components
in a React Application, allows changing the browser URL, and keeps the UI in
sync with the URL.
1.Create React App doesn't include
page routing.React Router is the most popular solution.
2.To add React Router in your application, run this in
the terminal from the root directory of the application:
npm i -D react-router-dom.
3.After installing the route in you applications. Keep
your components file inside a separate folder.
4.Then import
all the components to the main component.
5.Add a browser router to your app.js/index .js file . Router
is a parent is a component and can have only single child.
6.Now create links to our
components. Link component uses the to prop to
describe the location where the links should navigate to.
7.Then create Route for each
component.
Path: Path specifies a pathname we
assign to our component.
Element: It refers to the component
which will render on matching the path.
Example:
Output:
Comments
Post a Comment