0% found this document useful (0 votes)
200 views

React Js

ReactJS is a JavaScript library for building user interfaces that uses reusable components. It was developed by Jordan Walke at Facebook and is useful for building both web and mobile applications. Some key features of React include JSX syntax, reusable components, unidirectional data flow, virtual DOM, and performance. React allows creating single page applications with reusable UI components. To set up a React environment, NodeJS needs to be installed followed by using tools like Webpack, Babel or Create React App. Components are independent and reusable pieces of code that return HTML elements. Components can have properties called props and local state to make them dynamic.

Uploaded by

hktiwari88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views

React Js

ReactJS is a JavaScript library for building user interfaces that uses reusable components. It was developed by Jordan Walke at Facebook and is useful for building both web and mobile applications. Some key features of React include JSX syntax, reusable components, unidirectional data flow, virtual DOM, and performance. React allows creating single page applications with reusable UI components. To set up a React environment, NodeJS needs to be installed followed by using tools like Webpack, Babel or Create React App. Components are independent and reusable pieces of code that return HTML elements. Components can have properties called props and local state to make them dynamic.

Uploaded by

hktiwari88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

 ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable UI

components.

 React is a front-end library developed by Jordan Walke , who was a SE at Facebook.

 Useful for handling the view layer for web and mobile apps.

 Used in developing Whatsapp & Instagram

 React is an open-source, component-based front end library which is responsible only for the
view layer of the application.

 React can also render on the server using Node, and it can power native apps using React
Native.

 React is a JavaScript library for building user interfaces.

 React is used to build single page applications.

 React allows us to create reusable UI components.


ReactJs Features:
 JSX − JSX is JavaScript syntax extension. It isn't necessary to use JSX in React development, but it
is recommended.

 Components − React is all about components. You need to think of everything as a component.
This will help you maintain the code when working on larger scale projects.

 Unidirectional data flow and Flux − React implements one-way data flow which makes it easy to
reason about your app. Flux is a pattern that helps keeping your data unidirectional. ( Action
Store View )

 Virtual DOM

 Simplicity

 Performance

ReactJs Enviroment setup:

To Install NodeJS

https://nodejs.org/en/

You can install ReactJS in two ways

1.Using webpack and babel.

2.Using the create-react-app command.

Webpack is a module bundler (manages and loads independent modules). It takes dependent modules
and compiles them to a single (file) bundle. You can use this bundle while developing apps using
command line or, by configuring it using webpack.config file.

Babel is a JavaScript compiler and transpiler. It is used to convert one source code to other. Using this
you will be able to use the new ES6 features in your code where, babel converts it into plain old ES5
which can be run on all browsers.

Using create-react-app command:

1. Install create-react-app

npx create-react-app my-app

2. Go inside to project and then Run the project

npm start

 node_modules: It contains the React library and any other third party libraries needed.
 public: It holds the public assets of the application. It contains the index.html where React will
mount the application by default on the <div id="root"></div> element.

 src: It contains the App.css, App.js, App.test.js, index.css, index.js, and serviceWorker.js files.
Here, the App.js file always responsible for displaying the output screen in React.

 package-lock.json: It is generated automatically for any operations where npm package


modifies either the node_modules tree or package.json. It cannot be published. It will be
ignored if it finds any other place rather than the top-level package.

 package.json: It holds various metadata required for the project. It gives information to npm,
which allows to identify the project as well as handle the project?s dependencies.

 README.md: It provides the documentation to read about React topics.

Why React Jsx?

React uses JSX for templating instead of regular JavaScript. It is not necessary to use it.

 It is faster because it performs optimization while compiling code to JavaScript.

 It is also type-safe and most of the errors can be caught during compilation.

 It makes it easier and faster to write templates, if you are familiar with HTML.

import React from 'react';

class App extends React.Component {

render() {

return (

<div>

<h1>Header</h1>

<h2>Welcome to IMCS group</h2>

<p>This is the content!!!</p>

</div>

);

}
export default App;

Ex:

import React from 'react';

import ReactDOM from 'react-dom';

class Test extends React.Component {

render() {

return <h1>Hello World!</h1>;

ReactDOM.render(<Test />, document.getElementById('root'));

Setup:

npm install -g create-react-app

npx create-react-app myfirstreact

npm start

go inside the src/app.js file and modify content

import React, { Component } from 'react';

class App extends Component {

render() {

return (

<div className="App">

<h1>Hello World!</h1>
</div>

);

}}

export default App;

index.js

import React from 'react';

import ReactDOM from 'react-dom';

const myfirstelement = <h1>Hello React!</h1>

ReactDOM.render(myfirstelement, document.getElementById('root'));

Index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<meta name="viewport"

content="width=device-width, initial-scale=1" />

<title>React App</title>

</head> <body>

<div id="root"></div>

</body>

</html>

The ReactDOM.render() function takes two arguments, HTML code and an HTML element.

The purpose of the function is to display the specified HTML code inside the specified HTML element.
Example

Display a paragraph inside the "root" element:

ReactDOM.render(<p>Hello</p>, document.getElementById('root'));

The result is displayed in the <div id="root"> element:

<body>

<div id="root"></div>

</body>

What is JSX?
JSX stands for JavaScript XML.

JSX allows us to write HTML in React.

JSX makes it easier to write and add HTML in React.

JSX allows us to write HTML elements in JavaScript and place them in the DOM without
any createElement() and/or appendChild() methods.

import React from 'react';


import ReactDOM from 'react-dom';

const myelement = React.createElement('h1', {}, 'I do not use JSX!');

ReactDOM.render(myelement, document.getElementById('root'));

With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid JavaScript expression.

const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

Wrap two headers inside one DIV element:

const myelement = (
<div>
<h1>I am a Header.</h1>
<h1>I am a Header too.</h1>
</div>
);

JSX follows XML rules, and therefore HTML elements must be properly closed.

Example
Close empty elements with />

const myelement = <input type="text" />;

Components are like functions that return HTML elements.

React Components
Components are independent and reusable bits of code. They serve the same purpose as
JavaScript functions, but work in isolation and returns HTML via a render function.

Components come in two types, Class components and Function components, in this tutorial we
will concentrate on Class components.

Create a Class Component


When creating a React component, the component's name must start with an upper case letter.

The component has to 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
Create a Class component called Car

class Car extends React.Component {


render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Props
Another way of handling component properties is by using props.

Props are like function arguments, and you send them into the component as attributes.

class Car extends React.Component {


render() {
return <h2>I am a {this.props.color} Car!</h2>;
}
}

ReactDOM.render(<Car color="red"/>, document.getElementById('root'));

React components has a built-in state object.


The state object is where you store property values that belongs to the component.

When the state object changes, the component re-renders.

Creating the state Object

The state object is initialized in the constructor:

Example:

Specifiy the state object in the constructor method:

class Car extends React.Component {

constructor(props) {

super(props);

this.state = {brand: "Ford"};

render() {

return (

<div>

<h1>My Car</h1>

</div>

);

Changing the state Object


To change a value in the state object, use the this.setState() method.

When a value in the state object changes, the component will re-render, meaning that the
output will change according to the new value(s).

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 State holds information about the components.
as an argument.

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 comp

Stateless component can have Props. Stateless components cannot have State.

Props make components reusable. State cannot make components reusable.

Props are external and controlled by whatever renders the component. The State is internal and controlled by the React Component itse

Lifecycle of Components
Each component in React has a lifecycle which you can monitor and manipulate during its three
main phases.

The three phases are: Mounting, Updating, and Unmounting.

 Initial Phase
 getDefaultProps()
It is used to specify the default value of this.props. It is invoked before the
creation of the component or any props from the parent is passed into it.
 getInitialState()
It is used to specify the default value of this.state. It is invoked before the
creation of the component.
 Mounting Phase
 componentWillMount()
This is invoked immediately before a component gets rendered into the DOM. In
the case, when you call setState() inside this method, the component will
not re-render.
 componentDidMount()
This is invoked immediately after a component gets rendered and placed on the
DOM. Now, you can do any DOM querying operations.
 render()
This method is defined in each and every component. It is responsible for
returning a single root HTML node element. If you don't want to render anything,
you can return a null or false value.
 Updating Phase
 componentWillRecieveProps()
 shouldComponentUpdate()
 componentWillUpdate()
 render()
 componentDidUpdate()
 Unmounting Phase
 componentWillUnmount()

Forms

 Uncontrolled component

The uncontrolled input is similar to the traditional HTML form inputs.

 Controlled component

In HTML, form elements typically maintain their own state and update it according
to the user input. Here, the mutable state is kept in the state property and will be updated only
with setState() method
Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other
React features without writing a class. Hooks are the functions which "hook into" React state and
lifecycle features from function components. It does not work inside classes.

Rules of Hooks:

Hooks are similar to JavaScript functions, but you need to follow these two rules when using them.
Hooks rule ensures that all the stateful logic in a component is visible in its source code. These rules are:

1. Only call Hooks at the top level

2. 2. Only call Hooks from React functions

 npm install react@16.8.0-alpha.1 --save

 npm install react-dom@16.8.0-alpha.1 --save

Basic Hooks

useState

useEffect
useContext

Additional Hooks

useReducer

useCallback

useMemo

useRef

useImperativeHandle

useLayoutEffect

useDebugValue

function CustomCounter() {

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

const incrementCount = () => setCount(count + 1);

useDocumentTitle(`You clicked ${count} times`);

// useEffect(() => {

// document.title = `You clicked ${count} times`

// });

React Redux:

Redux is an open-source JavaScript library used to manage application state. React uses Redux for
building the user interface. It was first introduced by Dan Abramov and Andrew Clark in 2015.

 React Redux is the official React binding for Redux.

 It allows React components to read data from a Redux Store, and dispatch Actions to
the Store to update data.

 Redux does not have Dispatcher concept.

 Redux has an only Store whereas Flux has many Stores.

 The Action objects will be received and handled directly by Store.


Redux Architecture

React Redux requires React 16.8.3 or later version.

npm install redux react-redux --save

 STORE: A Store is a place where the entire state of your application lists. It manages the status
of the application and has a dispatch(action) function. It is like a brain responsible for all moving
parts in Redux.

 ACTION: Action is sent or dispatched from the view which are payloads that can be read by
Reducers. It is a pure object created to store the information of the user's event. It includes
information such as type of action, time of occurrence, location of occurrence, its coordinates,
and which state it aims to change.

 REDUCER: Reducer read the payloads from the actions and then updates the store via the state
accordingly. It is a pure function to return a new state from the initial state.

 Install a React Router


npm install react-router

 Create Components

The App component will be used as a tab menu. The other three components (Home),
(About) and (Contact) are rendered once the route has changed.

 Add a Router

we will add routes to the app. Instead of rendering App element like in the previous example, this time
the Router will be rendered. We will also set components for each route.

 Higher order components are JavaScript functions used for adding additional functionalities to
the existing component.

 These functions are pure, which means they are receiving data and returning values according
to that data

Higher Order Component (HOC) is wrapping around "normal" component and provide additional data
input. It is actually a function that takes one component and returns another component that wraps the
original one

import React from 'react';

var newData = { data: 'Data from HOC...', }

var MyHOC = ComposedComponent => class extends React.Component { componentDidMount() {


this.setState({ data: newData.data }); }

render() { return <ComposedComponent {...this.props} {...this.state} />; } };

class MyComponent extends React.Component {

render() { return ( <div> <h1>{this.props.data}</h1> </div> ) } }

export default MyHOC(MyComponent);

You might also like