What is ReactJS?
ReactJS is JavaScript library used for building reusable UI components. According to React official documentation, the following is the definition −
“React is a library for building composable user interfaces. It encourages the creation of reusable UI components, which present data that changes over time. Lots of people use React as the V in MVC. React abstracts away the DOM from you, offering a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native. React implements one way reactive data flow, which reduces the boilerplate and is easier to reason about than traditional data binding.”
What are the React 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.
· License − React is licensed under the Facebook Inc. Documentation is licensed under CC BY 4.0.
What are the advantages of React?
· Uses virtual DOM which is a JavaScript object. This will improve apps performance since JavaScript virtual DOM is faster than the regular DOM.
· Can be used on client and server side as well as with other frameworks.
· Component and data patterns improve readability, which helps to maintain larger apps.
What are the limitations of React?
· Covers only the view layer of the app, hence you still need to choose other technologies to get complete tooling set for development.
· Uses inline templating and JSX, which might seem awkward to some developers.
What is Babel?
Babel or Babel.js is a free and open-source JavaScript compiler and configurable transpiler used in web development. Babel allows software developers to write source code in a preferred programming language or markup language and have it translated by Babel into JavaScript, a language understood by modern web browsers.
How to setup React JS environment?
NodeJS and NPM are required to run ReactJS application. NodeJS is the platform needed for the ReactJS development.
What are the different ways to install the NodeJS?
You can install NodeJS in two ways
1. Using web pack and babel.
2. Using the create-react-app command.
How to install ReactJS globally?
C:\>npm install create-react-app -g
If you want to install in different drive for example in E- drive then
E:\>npm install create-react-app-g
What is useful extension required for ReactJS to code in Visual Studio Code?
Prettier – Code Formatter
Simple React Snippet
How to create the react app using command prompt?
Open the command prompt with the administrator. Install all Node JS and npm (Node package manager files). Once this is done type:
E:\>create-react-app myfirstreactapp
When you create a brand new React application what and all are created by default for you in your react application?
1. node_modules: Contains all the packages which are required to run the application. When npm is installed this folder by default created. If you see this folder you will get all dependent folders and files those are required by the react application.
2. public: It contains public assets of the react application which are used by in the application.
· favicon.ico : ico file which will displayed in react app.
· index.html : When the application starts this is the first page that is loaded. This will be the only html file in the entire application since React is generally Written using JSX which I will cover later. Also, this file has a line of code
<div
id=”root”></div>
. This line is very significant since all the application components are loaded into this div.
· manifest.json: It contains all the metadata of react application.
3. src:
· App.css: This is the CSS file corresponding to App Component
· App.js : This is the file for App Component. App Component is the main component in React which acts as a container for all other components.
· App.test.js : This is used for testing purpose
· index.css : The CSS file corresponding to index.js.
· index.js : Entry point to the application. This is the javascript file corresponding to index.html. This file has the following line of code which is very significant.
ReactDOM.render(<App />,
document.getElementById(‘root’));
· logo.svg: This represent the logo of the current application.
· serviceWorker.js : A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction. Today, they already include features like push notifications and background sync. In the future, service workers might support other things like periodic sync or geofencing. The core feature discussed in this tutorial is the ability to intercept and handle network requests, including programmatically managing a cache of responses.The reason this is such an exciting API is that it allows you to support offline experiences, giving developers complete control over the experience. Before service worker, there was one other API that gave users an offline experience on the web called AppCache. There are a number of issues with the AppCache API that service workers were designed to avoid. For more information visit official site (https://developers.google.com/web/fundamentals/primers/service-workers/)
4. .gitignore:
5. package-lock.json:
package-lock.json
is automatically generated for any operations where npm modifies either the node_modules
tree, or package.json
. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
6. package.json: This File has the list of node dependencies which are needed.
7. README.md: You will get some react commands in this file.
How to start the React JS application using light server or ?
To lunch the light server or development server... type npm start on the command prompt. Before that navigate to root project folder.
E:\>Cd myfirstreact
E:\>Npm start
How to install bootstrap in your react project?
Install the Bootstrap which will help us for styling purposes. Refer in the pages where you want to apply the bootstrap styles. You will get it in node_module.
E:\> myfirstreactapp >npm I bootstrap@4.1.1
How to stop the Light Server ?
To stop the light server press Ctrl+C . It will ask you Terminate batch job (Y/N)? Press Y to stop and N to continue to run the development server.
What is Hot Module Reloading?
Whenever we make some changes in the react code and save it, it automatically reflected in the browser. We no need to refresh the browser to see the changes. This is called Hot Module Reloading.
What are the two important import statements are required for any React application?
import React from 'react';
import ReactDOM from 'react-dom';
How to create ReactJS application form scratch?
Step - 1
Open the command prompt in administrated mode. And execute below commands one by one.
create-react-app shoppingcounter
cd shoppingcounter
npm I bootstrap@4.1.1
Code .
npm start
Step - 2
Open index.js file. And add the bootstrap reference.
import 'bootstrap/dist/css/bootstrap.css';
To check whether bootstrap working properly or not add a bootstrap button in the App.js file
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
<button type="button" class="btn btn-large btn-block btn-primary">Bootstap Button</button>
</a>
If you are able to see the styled bootstrap button then bootstrap is working properly else check for the fix what is causing the problem.
Step - 3
Create a new component. Component name should be always in camelCase notation.
Go to visual studio code editor.
Create folder “components” inside the “src” folder. Keep all components inside this folder from now.
Add a file Counter.jsx
Write below code in Counter.jsx file.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
render() {
return <h3>My First react application</h3>
// <button type="button" class="btn btn-large btn-block btn-primary">button</button>
}
}
export default Counter;
Step - 4
Open index.js file and import the Counter.jsx file as follows.
import Counter from './components/counter';
Step – 5
Replace the below code in index.js file
ReactDOM.render(<App />, document.getElementById('root'));
ReactDOM.render(<Counter />, document.getElementById('root'));
The complete code of index.js file now look like this.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';
ReactDOM.render(<Counter />, document.getElementById('root'));
serviceWorker.unregister();
Step – 6
Now add a new bootstrap button to the counter.jsx file. Note in jsx file it always returns only one element. If you want to return multiple elements then keep all the elements inside a <div></div> tag below is the complete code of counter.jsx file.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
render() {
return(
<div> <h3>My First react application</h3>
<button type="button" class="btn btn-primary">Increment</button>
</div>
);
}
}
export default Counter;
Instead of using <div></div> tag we can use <React.Fragment> </React.Fragment> for the same purpose. Below is the complete code after the change.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
render() {
return(
<React.Fragment>
<h3>My First react application</h3>
<button type="button" class="btn btn-primary">Increment</button>
</React.Fragment>
);
}
}
export default Counter;
What is a component in ReactJS?
What is state in ReactJS?
What is Object de-structuring?
In ReactJS whenever you found some repetition code we can de-structure that code. See the below highlighted code
counter.jsx
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
render() {
return (
<React.Fragment>
<h3>{this.formatCount()}</h3>
<button type="button" class="btn btn-primary">Increment</button>
</React.Fragment>
);
}
formatCount() {
return this.state.count === 0 ? <h5>Zero</h5> : this.state.count
}
}
export default Counter;
After object de-structuring the code will look like this.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
render() {
return (
<React.Fragment>
<h3>{this.formatCount()}</h3>
<button type="button" class="btn btn-primary">Increment</button>
</React.Fragment>
);
}
formatCount() {
const {count}= this.state;
return count === 0 ? <h5>Zero</h5> : count
}
}
export default Counter;
What are the different types of state present in ReactJS?
In ReactJS two types of components present.
- Stateless ReactJS Component
- All function based components can be considered as stateless ReactJS components.
- Stateless ReactJS Components are pure JavaScript functions so, we don’t need to have state.
- Stateful ReactJS Component
- All class based components can be considered as stateful ReactJS components.
- Stateful ReactJS Components inherits the class React.Component so, state gets inherited.
What is ReactJS Component Lifecycle?
React component has 3 lifecycle methods. ReactJS is a component based java script library. In every ReactJS application components are rendered onto virtual DOM. Before/After rendering onto the virtual DOM every component goes through some of the methods. We call these methods as ReactJS Component Lifecycle Methods. We can categorize these methods into three based on component initialization, updation and destruction. They are
· Mounting Methods(initialization)
· Updating Methods (updation)
· Unmounting Methods (destruction)
ReactJS Component Mounting Methods (Initialization)
- These methods are called when the component is being rendered for the first time.
- Whenever a component is rendered the first method called is “constructor”.
- In the constructor we can provide default/initial data for component state and props.
- After constructor, Mounting Methods will be called. They are
- static getDerivedStateFromProps:
- It is called just before
render
method. - It takes two parameters
props
andstate
and it should return anobject
with data ornull
for empty object to update the state. - render:
- It is called after method
componentWillMount
. It simply renders the react component onto the DOM by using props and state of the component. - componentDidMount:
- It is called after method
render
. - In this method we can do stuff like calling REST API to update the state, etc.
ReactJS Component Updating Methods (Updation)
- We know ReactJS is very quick to user actions. Some times we need to updated DOM based on user actions. To update the React DOM with respect to user actions we use ReactJS component updating methods. They are
- shouldComponentUpdate:
- It is called before component re-renders right after change in props of state.
- It’s a boolean method which tells react to re-render the DOM or not. Default return value for this method is
true
. - render:
- It will update the DOM with new props and new state.
- componentDidUpdate:
- It is called immediately after updating occurs. It is not called for the initial render.
- It works just like method
componentDidMount
.
ReactJS Component Unmounting Methods (Destruction)
- It has only one method
componentWillUnmount
which executed just before ReactJS component removed. - It is called as “cleanup method”. Because, here we can remove the unused data, unwanted network requests, etc.
- We should not call method
setState
here because the component will never be re-rendered.
How to set attributes in .JSX files in ReactJS?
You can set attributes inline or keep it separately and call in the jsx attribute. See the below example.
render() {
return (
<React.Fragment>
<span className="badge badge-primary m-2" >
{this.formatCount()}
</span>
<button type="button" className="btn btn-secondary m-2">
Increment
</button>
</React.Fragment>
);
}
In the above example we set the span and button attributes inline. If you want to in separately we can do as follows.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
styles ={
fontSize:20,
fontWeight:'Bold'
};
render() {
return (
<React.Fragment>
<span style={this.styles} className="badge badge-primary m-2" >{this.formatCount()}</span>
<button type="button" className="btn btn-secondary m-2">Increment</button>
</React.Fragment>
);
}
formatCount() {
const {count}= this.state;
return count === 0 ? 'Zero' : count
}
}
export default Counter;
To make it inline just remove the external styles attribute and put all the required styles in {{ }} inline as follows.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
render() {
return (
<React.Fragment>
<span style={{fontSize:60}} className="badge badge-primary m-2" >{this.formatCount()}</span>
<button type="button" className="btn btn-secondary m-2">Increment</button>
</React.Fragment>
);
}
formatCount() {
const {count}= this.state;
return count === 0 ? 'Zero' : count
}
}
export default Counter;
How to render classes dynamically?
Instead of hard coding the styles we can apply the styles dynamically. Let say if some condition satisfies then the style will be one and if not satisfied then it will show in different style. In this case we have to apply the styles dynamically rather than hard coded. See the below code.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
render() {
return (
<React.Fragment>
<span style={{fontSize:60}} className={this.getBadgeClasses()} >{this.formatCount()}</span>
<button type="button" className="btn btn-secondary m-2">Increment</button>
</React.Fragment>
);
}
formatCount() {
const {count}= this.state;
return count === 0 ? 'Zero' : count
}
getBadgeClasses()
{
let styleClasses="badge m-2 badge-";
styleClasses+= this.state.count === 0 ? "warning" : "primary";
return styleClasses;
}
}
export default Counter;
How to render list of items in ReactJS?
Or
What is the use of map method?
ReactJS does not supports any for loop or if statements. If you want to render a list of items you need to use map method with arrow function. Below is the code:
listofitems.jsx
import React, { Component } from 'react';
class ListofItems extends Component {
state = {
Items: ["Vegitables", "ColdDrinks", "IceCream", "Fruits"]
}
render() {
return (
<div>
<ul>
{this.state.Items.map(x => <li key={x}>{x}</li>)}
</ul>
</div>
);
}
}
export default ListofItems;
Change the code in index.js file to get the output:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';
import ListofItems from './components/listofitems';
ReactDOM.render(<ListofItems />, document.getElementById('root'));
serviceWorker.unregister();
How to achieve conditional rendering?
Conditional rendering means it will check if condition satisfied then will render the items else will not show anything or else will some user friendly message.
See the below code:
import React, { Component } from 'react';
class ListofItems extends Component {
state = {
Items: []
}
CheckItemsInStock()
{
if(this.state.Items.length === 0)
return <p>There are no items to show</p>
return <ul>
{this.state.Items.map(x => <li key={x}>{x}</li>)}
</ul>
}
render() {
return (
<div>
{this.CheckItemsInStock()}
</div>
);
}
}
export default ListofItems;
In the above code as Items array is empty it will show the output as : There are no items to show
Now add some items and test the code. It will render the list of items.
If you want to show extra message to check the array is empty or not before the function call, you can use logical && operator. See the below code:
render() {
return (
<div>
{this.state.Items.length === 0 && 'Please enter some items in to the Item List:'}
{this.CheckItemsInStock()}
</div>
);
}
How to handle Events in ReactJS?
See the below code. When button is clicked the count value increases by 1.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
render() {
return (
<React.Fragment>
<span style={{ fontSize: 60 }} className={this.getBadgeClasses()} >{this.formatCount()}</span>
<button onClick={this.handleIncrement} type="button" className="btn btn-secondary m-2">Increment</button>
</React.Fragment>
);
}
handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
}
formatCount() {
const { count } = this.state;
return count === 0 ? 'Zero' : count
}
getBadgeClasses() {
let styleClasses = "badge m-2 badge-";
styleClasses += this.state.count === 0 ? "warning" : "primary";
return styleClasses;
}
}
export default Counter;
How to pass arguments to a function in ReactJS?
See the below code:
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
render() {
return (
<React.Fragment>
<span style={{ fontSize: 60 }} className={this.getBadgeClasses()} >{this.formatCount()}</span>
<button onClick={()=>this.handleIncrement({product:1})} type="button" className="btn btn-secondary m-2">Increment</button>
</React.Fragment>
);
}
handleIncrement = (product) => {
this.setState({ count: this.state.count + 1 });
}
formatCount() {
const { count } = this.state;
return count === 0 ? 'Zero' : count
}
getBadgeClasses() {
let styleClasses = "badge m-2 badge-";
styleClasses += this.state.count === 0 ? "warning" : "primary";
return styleClasses;
}
}
export default Counter;
No comments:
Post a Comment