4.ReactNotes
4.ReactNotes
4.ReactNotes
REACT JS
ES6
What is ES6??
JavaScript has had many versions over the years and ES6 is one of the JavaScript
versions.
ES6 was released in 2015 and ES6 refers to version 6 of the ECMAScript programming
language. ECMAScript is the standardized name for JavaScript. It is a major
enhancement to the JavaScript language, and adds many more features intended to
make large-scale software development easier.
Think of let as the new var. It is used to create a variable for which the value may
change even after it’s declared. It doesn’t supports hoisting.
const is used to create a variable for which the value will never change after it’s
declared. JavaScript will give you an error if you try to update the value of a const
variable. It doesn’t supports hoisting.
For eg,
let mAge = 28
const endpoint = “https://api.rest.com/v1/”
Old Method:
// Function Body
Arrow Functions:
// Function Body
const mFunc = arg1 => arg1*2 // If there is a single line of code then you can get rid of
curly braces and the return statement.
When you copy a variable in another like below example, for primitive types the value
is copied but for reference types the pointer is copied.
const mVar1;
Rest is used to merge all the function arguments in an array. This helps to create a
function which accepts variable argument.
For eg,
map() - Used to iterate list items. Accepts a callback function which runs on all the
items. It returns an array with same length as the initial array.
reduce() - Used to iterate list or object items. Accepts two parameter an accumulator
and a callback function. But instead of returning the result to array, it passes it to the
next item.
filter() - Used to filter out data from a list. It returns an array with the filtered data.
})
}, 0);
return true/false;
});
For example,
$.get('some-url', callbackFunc);
You cannot write it after the get() method because you have no way of knowing when
the response is received. So your only option is to put the details call inside the first
callback function.
Rejected: The operation did not complete and an error can be thrown.
JavaScript classes also supports Inheritance. To inherit the properties and methods of
another class, the extends keyword is used.
this.name = name;
this.age = age;
this.job = job;
For example,
The entire React application can be modeled as a set of independent, isolated and
reusable components. In other words you can say components are the building blocks
of React App. These components are put together to design complex layouts.
React makes it painless to create interactive UIs. It has a concept called state for this
purpose.
Some of the websites built with React - Facebook, Netflix, Instagram, Twitter, Airbnb,
Nike, MakeMyTrip, Codepen, Snapchat, Prime Videos and many many more.
When you open a SPA in browser. It brings all the content in the first load itself. Now
whenever you change routes or click on dropdowns it doesn’t needs to refresh the
page to fetch data because all the required data is already present.
Some latest Frontend Frameworks like React, Angular, Vue, Ember etc enable us to
create SPAs.
cd my-app
npm start
Once the local server starts, then open http://localhost:3000/ to see your app.
For example,
entry.appendChild(document.createTextNode(firstName));
list.appendChild(entry);
JSX
<ol><li>{firstname}</li></ol>
For eg,
const greetings = <h1>Welcome, {firstname}</h1>
For eg,
<a className=”GoogleLink” href=”https://www.google.com” >Link</a>
3. Dynamic Attributes.
For eg,
const MenuItem = () {
}
export default MenuItem;
When React creates component/element, it calls this method, which takes three
arguments.
});
Key helps React identify which components have changed. All the elements inside an
array should have a unique key.
For eg,
<div styles={{backgroundColor: ‘blue’, fontSize: ‘16px’}}>Hello<div>
const styles = {
backgroundColor: ‘blue’,
fontSize: ‘16px’
}
<div styles={styles}>Hello<div>
For eg,
import ‘./App.css’;
.Heading {
color: red;
For eg,
background-color: white;
For eg,
return() {
<div>
<h3>Blog 1</h3>
</div>
return (<div>
<h3>{props.title}</h3>
<p>{props.desc}</p>
</div>);
}
To define class based components we use ES6 class syntax. A class-based component
inherits the Component class of React. This Component class gives the component
access to some properties and methods like state and setState etc.
It has a render method. So everytime the setState method is called it results in calling
the render method.
return true/false;
It is the tree representation of the HTML document. In other words, it shows the
structure of an HTML document.
When you update HTML elements, it results in repaints and reflows. Both of these are
pretty heavy tasks. That’s why updating DOM is a heavy process. Frequently, updating
DOM results in performance issues, in turn making the application slow.
//Component Code
}
● Write about What is CSS Modules and Why do you need it??
● Difference between stateful and stateless component?
● Difference between props and state?
● Limitation of PureComponent
● Create the counter app with Count in Topbar. //Just make a couple of changes
instead of Count. Make it like and dislike. Two buttons to inc/dec likes. Two buttons
to inc/dec dislikes.
To Install
Axios is the one of the most popular library to handle HTTP requests in React.
To install Axios:
axios.get(“url”)
.then((response) => {
// handle success
})
.catch((error) => {
// handle error
})
console.log(‘ABC’)
return Promise.resolve(reponse);
}
Putting the keyword async before a function tells the function to return a Promise.
If the code returns something that is not a Promise, then JavaScript automatically
wraps it into a resolved promise with that value.
Inside a function marked as async, you are allowed to place the await keyword in front
of an expression that returns a Promise. When you do, the execution is paused until
the Promise is resolved.
const postData={}
.then((response) => {
// handle success
})
.catch((error) => {
// handle error
})
.then((response) => {
// handle success
})
.catch((error) => {
// handle error
})
To map these endpoints with components use <Route path={} render={() =>
<Component />}>
To use the above components we need to wrap the main App in the BrowserRouter
component.
For eg,
<Route path={“/details”} render={() => <DetailsPage />} for the details page
To select one route at a time, we can use Switch component. With switch the sequence
matters a lot.
To pass the url params, you need to add “:id” in the endpoint to create a variable for id.
To pass this id down the component just spread and send the props passed by the
Router to component. Now you can access this variable in the match object.
For eg,
API Endpoints:
For eg,
<Route exact to={‘/’} render={() => <HomePage />} //We are using exact so only “/”
should match for HomePage.
<Route render={() => <NotFound />} /> //Just add this route at the last so that if nothing
matches it just renders this component.
For eg,
For eg,
Page Loader. It is required by almost all the components which load data from
backend. Now to show a loader you can simply pass some props and based on that
either you can show the actual content or the loader.
On submit, we can extract values from the form or fetch it from our state and send it to
the backend using an HTTP post call.
Usage:
import PropTypes from ‘prop-types’;
VideoCard.propTypes = {
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
thumbnail: PropTypes.string
Usage:
VideoCard.defaultProps = {
isPlaylistCard: false
To install Redux:
To install React-Redux:
return {
topbarTotLikes: globalState.totalLikes
return {
Class-based Components
state = {
totalCount: 0,
Hooks:
Class-based Components
increaseCount = () => {
this.setState({totalCount: updatedVal})
}
Hooks:
Axios.get()
.then(() => {
})
})
Run command firebase init to initialize firebase for your project -> Choose hosting ->
Choose your firebase project -> Add path to your directory where you have code for
deployment(build) -> Select whether it's a SPA(Select Yes) -> Select No to prevent
firebase from overriding your index.html.
Run command firebase serve to check if everything is configured properly.
It is a module bundler primarily for JavaScript, but it can transform front-end assets
like HTML, CSS, and images if the corresponding plugins are included.
It takes modules with dependencies and generates static assets representing those
modules.