You are on page 1of 20

ReactJS is JavaScript library used for building reusable UI components, UserInterfaces

React is a library for building composable user interfaces It encourages the creation of
reusable UI components, which present data that changes over time

React --> Client java script Library useful build User Interfaces .React is almost all
developed with components. reusability purpose we will use components concept.

Why React?
It is providing Single page Applications (SPA),Rich Internet Applications( RIA).
It has special feature called VIRTUAL DOM
UI state becomes difficult to handle with vanilla Javascript
Focus on Business logic, not preventing your app from exploring (Frameworks
Community)
Huge Ecosystem, Active Community, High Performance

React Alternatives:
Angular, Vue

SPA
Only One HTML page Content is re rendered on client
Only one ReactDOMrender() call

MPA(Multiple)
Multiple HTML pages content is rendered on Server
one ReactDOMrender() call per widget

Who introduced React?


Developed by Jordan walker , who is SoftwareEngineer at facebook.

REACTJS is useful for developing the both Web, mobile applications development
purpose.

React Native is useful for mobile application development purpose.

React is used in popular big applications like facebook, whatsapp, instagram, udemy,
etc…

React data displaying can be done in Unidirectional flow -->html --> model

React. JS was first used in 2011 for Facebook's Newsfeed feature. Facebook Software
Engineer, Jordan Walke, created it. The create-react-app version 2.0 package was released in
October 2018.
Prerequirments
HTML 5
CSS 3
JS
ES6-ECMA Script 6

Let & Const:


let and const basically replace var You use let
instead of var and const instead of var if you plan on
never re-assigning this "variable" (effectively turning it into a
constant therefore)

function varTest() {
var x = 1;
{
var x = 2; // same variable!
Console.log(x); // 2
}
Console.log(x); // 2
}

function letTest() {
let x = 1;
{
let x = 2; // different variable
console.log(x); // 2
}
Console.log(x); // 1
}

// NOTE: Constants can be declared with uppercase or lowercase, but a common


// convention is to use all-uppercase letters

// define MY_FAV as a constant and give it the value 7


const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable


MY_FAV = 20;

// MY_FAV is 7
Console.log('my favorite number is: ' + MY_FAV);
// trying to redeclare a constant throws an error - Uncaught SyntaxError: Identifier
'MY_FAV' has already been declared
const MY_FAV = 20;

// the name MY_FAV is reserved for constant above, so this will fail too
var MY_FAV = 20;

// this throws an error too


let MY_FAV = 20;

// it's important to note the nature of block scoping


if (MY_FAV === 7) {
// this is fine and creates a block scoped MY_FAV variable
// (works equally well with let to declare a block scoped non const variable)
let MY_FAV = 20;

// MY_FAV is now 20
Console.log('my favorite number is ' + MY_FAV);

// this gets hoisted into the global context and throws an error
var MY_FAV = 20;
}

// MY_FAV is still 7
Console.log('my favorite number is ' + MY_FAV);

// throws an error - Uncaught SyntaxError: Missing initializer in const declaration


const FOO;

// const also works on objects


const MY_OBJECT = {'key': 'value'};

// Attempting to overwrite the object throws an error - Uncaught TypeError: Assignment


to constant variable
MY_OBJECT = {'OTHER_KEY': 'value'};

// However, object keys are not protected,


// so the following statement is executed without problem
MY_OBJECTkey = 'otherValue'; // Use Objectfreeze() to make object immutable

// The same applies to arrays


const MY_ARRAY = [];
// It's possible to push items into the array
MY_ARRAYpush('A'); // ["A"]
// However, assigning a new array to the variable throws an error - Uncaught TypeError:
Assignment to constant variable
MY_ARRAY = ['B'];

Arrow functions:
Arrow functions are a different way of creating functions in
JavaScript Besides a shorter syntax, they offer advantages
when it comes to keeping the scope of the this keyword
function callMe(name) {
console.log(name);
}
When having no arguments, you have to use empty
parentheses in the function declaration:
const callMe = () => {
console.log(‘Srini!');
}
When having exactly one argument, you may omit the
parentheses:
const callMe = name => {
console.log(name);
}
When just returning a value, you can use the following
shortcut:
const returnMe = name => name

Export and Import :


In React projects (and actually in all modern JavaScript
projects), you split your code across multiple JavaScript
files - so-called modules You do this, to keep each file/
module focused and manageable
To still access functionality in another file, you need export
(to make it available) and import (to get
access) statements

Classes
Classes are a feature which basically replace constructor
functions and prototypes You can define blueprints for
JavaScript objects with them
Like this:
class Person {
constructor () {
thisname = ‘Srinivas’;
}
}

const person = new Person();


console.log(personname); // prints ‘Srinivas’

In the above example, not only the class but also a property
of that class (=> name ) is defined They syntax you see
there, is the "old" syntax for defining properties In modern
JavaScript projects (as the one used in this course), you
can use the following, more convenient way of defining
class properties:
class Person { name = ‘Srini’; }

const person = new Person();


console.log(personname); // prints ‘Srinivas’
You can also define methods Either like this:
class Person {
name = ‘Srinivas’;
printMyName () {
console.log(this.name); // this is required to refer
to the class!
}
}

const person = new Person();


person.printMyName();
Or like this:
class Person {
name = ‘Srinivas’;
printMyName = () => {
console.log(thisname);
}
}

const person = new Person();


person.printMyName();

The second approach has the same advantage as all arrow


functions have: The this keyword doesn't change its
reference
You can also use inheritance when using classes:
class Human {
species = 'human';
}

class Person extends Human {


name = ‘Srinivas’;
printMyName = () => {
console.log(thisname);
}
}

const person = new Person();


personprintMyName();
console.log(personspecies); // prints 'human'

Spread & Rest Operator


The spread and rest operators actually use the same
syntax:
Yes, that is the operator - just three dots It's usage
determines whether you're using it as the spread or rest
operator
Using the Spread Operator:
The spread operator allows you to pull elements out of an
array (=> split the array into a list of its elements) or pull the
properties out of an object Here are two examples:
const oldArray = [1, 2, 3];
const newArray = [oldArray, 4, 5]; // This now is [1, 2,
3, 4, 5];
Here's the spread operator used on an object:
const oldObject = {
name: ‘Srinivas’
};
const newObject = {
oldObject,
age: 28
};
newObject would then be
{
name: ‘Srinivas’,
age: 28
}
The spread operator is extremely useful for cloning arrays and objects Since both are
reference types (and not primitives), copying them safely (ie preventing future
mutation of the copied original) can be tricky With the spread operator you have an easy
way of creating a (shallow!) clone of the object or array

Destructuring:
Destructuring allows you to easily access the values of arrays or objects and assign
them to variables
Here's an example for an array:
const array = [1, 2, 3];
const [a, b] = array;
console.log(a); // prints 1
console.log(b); // prints 2
console.log(array); // prints [1, 2, 3]
And here for an object:
const myObj = {
name: ‘Srinivas’,
age: 28
}
const {name} = myObj;
console.log(name); // prints ‘Srinivas’
console.log(age); // prints undefined
console.log(myObj); // prints {name: ‘Srinivas’, age: 28}
Destructuring is very useful when working with function
arguments Consider this example:
const printName = (personObj) => {
console.log(personObjname);
}
printName({name: ‘Srinivas’, age: 28}); // prints ‘Srinivas’
Here, we only want to print the name in the function but we pass a complete person
object to the function Of course this is no issue but it forces us to call personObjname
inside of our function We can condense this code with destructuring:
const printName = ({name}) => {
console.log(name);
}
printName({name: ‘Srinivas’, age: 28}); // prints ‘Srinivas’)
We get the same result as above but we save some code By destructuring, we simply
pull out the name property and store it in a variable/ argument named name which we
then can use in the function body

Components:
Components are the core building block of React apps Actually, React really is just a
library for creating components in its core A typical React app therefore could be
depicted as a component tree - having one root component ("App") and then an
potentially infinite amount of nested child components

Each component needs to return/ render some JSX code - it defines which HTML code
React should render to the real DOM in the end JSX is NOT HTML but it looks a lot like
it Differences can be seen when looking closely though (for example className in JSX
vs class in "normal HTML") JSX is just syntactic sugar for JavaScript, allowing you to
write HTMLish code instead of nested ReactcreateElement() calls When creating
components, you have the choice between two different ways:
1 Functional components (also referred to as "presentational", "dumb" or "stateless"
components - more about this later in the course) => const cmp = () => { return
<div>some JSX</div> } (using ES6 arrow functions as shown here is recommended but
optional)
2 class-based components (also referred to as "containers", "smart" or "stateful"
components) => class Cmp extends Component { render () {
return <div>some JSX</div> } }
We'll of course dive into the difference throughout this course, you can
already note that you should use 1) as often as possible though It's the
best-practice
props and state are CORE concepts of React Actually, only changes in props and/ or
state trigger React to rerender your components and potentially update the DOM in
the browser

Props
props allow you to pass data from a parent (wrapping) component to a child
(embedded) component
Example:
AllPosts Component:
const posts = () => {
return (
<div>
<Post title="My first Post" />
</div>
);
}
Here, title is the custom property (prop ) set up on the custom Post component We
basically replicate the default HTML attribute behavior we already know
(eg <input type="text"> informs the browser about how to handle that input)
Post Component:
const post = (props) => {
return (
<div>
<h1>{propstitle}</h1>
</div>
);
}
The Post component receives the props argument You can of course name this
argument whatever you want - it's your function definition, React doesn't care! But
React will pass one argument to your component function => An object, which contains
all properties you set up on <Post /> {propstitle} then dynamically outputs the title
property of the props object - which is available since we set the title property inside
AllPosts component (see above)

State
Whilst props allow you to pass data down the component tree (and hence trigger an UI
update), state is used to change the component, well, state from within Changes to
state also trigger an UI update
Example:
NewPost Component:
class NewPost extends Component { // state can only be
accessed in class-based components!
state = {
counter: 1
};

render () { // Needs to be implemented in class-based


components! Needs
You shouldn't need it right now - but in case you ever want to dive in, here's the official
React documenation: https://reactjsorg/

Had issues with the Codepen demo? Here's the finished source
code: https://codepenio/anon/pen/MELQaQ

Jsx we will write inside javascript we will arite html code directly

Babel will take care of converting this

Why React?
UI State becomes difficult t handle with vanilla Javascript
Focus On Business Logic , not on preventing your App from exploding
Huge Ecosystem, Active Community, High performance

Alternatives?
Angular,Vue,Jquery(NOT SO MUCH)

2 kinds of Applications
SPA
Only One html page content is re rendered on Client
Typically Only one ReactDOMrendere() Call
Mutipage App

Multiple HTML Pages, content is rendered on server


One ReactDOMrender() call per “widget”

Nextgen- JS
Codepenio

Arrow Functions
Const myfun = () =>{…}

**** No more issues with this keyword

Exports &imports(Modules)
Const person ={
Name:’Srini’
}
Export default person
Export const clean = () =>{}
Export const baseData=20;

Import person from ‘/personjs’


Import prs from ‘/personjs’

Classes
Class Person{
Name =”srini”
Call=()=>{}
}

Const myperson = new Person();


Mypersoncall();

ES6:
Constructor(){
ThismyProperty = “value”;
}

Es7:
myProperty =”value”

Spread& Rest Operators( …)


Used to split up array elements Or Object Properties
Const newr= […old array,3,2]
Const newobj = {…oldobj, newpro:8}

Rest:used to manage a list of function arguments into an array


Function sortArgs(… args){
Return argssort();
}

Destructuring:
Easily extract array elements or object properties and store them in variables

Array destructuring:
[a,b]=[“hello”,”Max”]
Console.log(a);
Const numbers = [1,2,3];
[num1,,num3]=numbers;
cl(num3);

Object Destructuring:
{name}= {name:’Srini’,age:34}
Console.log(name);

Reference and Primitive type


Const number =1;
Const num2 = number;
Console.log(num2);

Refreshing Array:
Numbermap(return number*2)
State

Whilst props allow you to pass data down the component tree (and hence trigger an
UI update), state is used to change the component, well, state from within Changes to
state also trigger an UI update

Example:

NewPost Component:

1. class NewPost extends Component { // state can only be accessed in class-based


components!
2. state = {
3. counter: 1
4. };
5.
6. render () { // Needs to be implemented in class-based components! Needs to return
some JSX!
7. return (
8. <div>{thisstatecounter}</div>
9. );
10. }
11. }

Here, the NewPost component contains state Only class-based components can
define and use state You can of course pass the state down to functional components,
but these then can't directly edit it

state simply is a property of the component class, you have to call it state though - the
name is not optional You can then access it via thisstate in your class JSX code (which
you return in the required render() method)
Whenever state changes (taught over the next lectures), the component will re-render
and reflect the new state The difference to props is, that this happens within one and
the same component - you don't receive new data (props ) from outside!

In the last lecture, we saw that you can react to the onClick event - but to which other
events can you listen? You can find a list of supported events
here: https://reactjsorg/docs/eventshtml#supported-events

Clipboard Events
Event names:

1. onCopy onCut onPaste

Properties:

1. DOMDataTransfer clipboardData

Composition Events

Event names:

1. onCompositionEnd onCompositionStart onCompositionUpdate

Properties:

1. string data

Keyboard Events

Event names:

1. onKeyDown onKeyPress onKeyUp

Properties:

1. boolean altKey
2. number charCode
3. boolean ctrlKey
4. boolean getModifierState(key)
5. string key
6. number keyCode
7. string locale
8. number location
9. boolean metaKey
10. boolean repeat
11. boolean shiftKey
12. number which

Focus Events

Event names:

1. onFocus onBlur

These focus events work on all elements in the React DOM, not just form elements

Properties:

1. DOMEventTarget relatedTarget

Form Events

Event names:

1. onChange onInput onInvalid onSubmit

For more information about the onChange event, see Forms

Mouse Events

Event names:

1. onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit


2. onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter
onMouseLeave
3. onMouseMove onMouseOut onMouseOver onMouseUp

The onMouseEnter and onMouseLeave events propagate from the element being left
to the one being entered instead of ordinary bubbling and do not have a capture phase

Properties:

1. boolean altKey
2. number button
3. number buttons
4. number clientX
5. number clientY
6. boolean ctrlKey
7. boolean getModifierState(key)
8. boolean metaKey
9. number pageX
10. number pageY
11. DOMEventTarget relatedTarget
12. number screenX
13. number screenY
14. boolean shiftKey

Selection Events

Event names:

1. onSelect

Touch Events

Event names:

1. onTouchCancel onTouchEnd onTouchMove onTouchStart

Properties:

1. boolean altKey
2. DOMTouchList changedTouches
3. boolean ctrlKey
4. boolean getModifierState(key)
5. boolean metaKey
6. boolean shiftKey
7. DOMTouchList targetTouches
8. DOMTouchList touches

UI Events

Event names:

1. onScroll

Properties:

1. number detail
2. DOMAbstractView view

Wheel Events

Event names:

1. onWheel

Properties:
1. number deltaMode
2. number deltaX
3. number deltaY
4. number deltaZ

Media Events

Event names:

1. onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted


2. onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay
3. onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend
4. onTimeUpdate onVolumeChange onWaiting

Image Events

Event names:

1. onLoad onError

Animation Events

Event names:

1. onAnimationStart onAnimationEnd onAnimationIteration

Properties:

1. string animationName
2. string pseudoElement
3. float elapsedTime

Transition Events

Event names:

1. onTransitionEnd

Properties:

1. string propertyName
2. string pseudoElement
3. float elapsedTime

Other Events
Event names:

1. onToggle

42,43 class

• Conditional Rendering: https://reactjsorg/docs/conditional-renderinghtml


• Lists & Keys: https://reactjsorg/docs/lists-and-keyshtml

Don't skip this lecture - and keep it open in a separate browser tab when you go
through the next lecture - sorry for the small inconvenience at this point!

In the next lecture, we'll use a styling solution named "CSS modules" I'll explain what it
is and how it works over the next lectures

The way we unlock it changed a little bit though

In the next lecture, we'll eject from the project created with create-react-app (I'll show
how that is done in the next lecture and that process will be exactly the same)

We'll then replace some code in a newly added webpack config file (it'll be available
after ejecting)

In the video, I'll look for an entry that starts like this (in the webpackconfigjs file):

1. {
2. test: /\css$/,
3.
4. }

and I then edit this entry

This entry now looks slightly different You'll have to find the following part in
your webpackconfigjs file:

1. {
2. test: cssRegex,
3. exclude: cssModuleRegex,
4.
5. }

and then edit that entry

Finally, it should look like this:

1. {
2. test: cssRegex,
3. exclude: cssModuleRegex,
4. use: getStyleLoaders({
5. importLoaders: 1,
6. modules: true,
7. localIdentName: '[name]__[local]__[hash:base64:5]'
8. }),
9. }

You can ignore me editing the webpackconfigprodjs file - with the latest version of
create-react-app, ejecting only gives you ONE webpack config file (which you edit as
described above)

---

Alternatively, you can now also use CSS modules without ejecting (you still can though,
it won't be a problem) In a non-ejected project created with create-react-app, you can
use CSS modules as described here: https://facebookgithubio/create-react-
app/docs/adding-a-css-modules-stylesheet

CSS Modules are a relatively new concept (you can dive super-deep into them
here: https://githubcom/css-modules/css-modules) With CSS modules, you can write
normal CSS code and make sure, that it only applies to a given component

It's not using magic for that, instead it'll simply automatically generate unique
CSS class names for you And by importing a JS object and assigning classes from
there, you use these dynamically generated, unique names So the imported JS object
simply exposes some properties which hold the generated CSS class names as values

Example:

In Postcss File

1. Post {
2. color: red;
3. }

In Post Component File


1. import classes from '/Postcss';
2.
3. const post = () => (
4. <div className={classesPost}></div>
5. );

Here, classesPost refers to an automatically generated Post property on the


imported classes object That property will in the end simply hold a value
like Post__Post__ah5_1

So your Post class was automatically transformed to a different class


( Post__Post__ah5_1 ) which is unique across the application You also can't use it
accidentally in other components because you don't know the generated string! You can
only access it through the classes object And if you import the CSS file (in the same
way) in another component, the classes object there will hold a Post property which
yields a different (!) CSS class name Hence it's scoped to a given component

By the way, if you somehow also want to define a global (ie un-transformed) CSS class
in such a css file, you can prefix the selector with :global

Example:

:global Post { }

Now you can use className="Post" anywhere in your app and receive that styling

• Using CSS Modules in create-react-app Projects: https://mediumcom/nulogy/how-to-


use-css-modules-with-create-react-app-9e44bec2b5c2
• More information about CSS Modules: https://githubcom/css-modules/css-modules
Debugging
React debugging
Error Boundary

• Error Boundaries: https://reactjsorg/docs/error-boundarieshtml


• Chrome Devtool Debugging: https://developersgooglecom/web/tools/chrome-
devtools/javascript/
Deep Components:

You might also like