Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

ReactJS - Interlace your Interface

Introduction to ReactJS
This course introduces you to one of the popular JavaScript
frameworks, React.js or ReactJS. In this course, you will learn about:

 Introduction to ReactJS
 Basic Concepts in ReactJS
 Using Elements and Components
 Handling Events
 Usage of Keys and Ref
 Best Practice while using ReactJS

What is React?
 An Open source library developed and maintained by the developers of Facebook,
Instagram and also a larger community of contributors.
 A declarative, efficient, and flexible JavaScript library for building user interfaces.
 Makes developing a large scale, single page application easier.
 Supports all the syntax of ECMA Script 2015/ES6.
 Can perform client-side as well as server side rendering.

Virtual DOM
What is exciting here?
For creating dynamic UI, DOM was never an optimized solution. Consider a page displaying a
list containing 10 items and one is getting updated. While performing update, DOM will rebuild
the entire list making it work 10 times more than what is necessary. This inefficiency can be
overcome using Virtual DOM.

Virtual DOM is an abstract, lightweight copy of DOM. It can be changed as and when we
want and then can be saved to the real DOM. Whenever a change occurs, Virtual DOM
efficiently rerenders the DOM. It is much faster than DOM.

Virtual DOM (Document Object Model) has the same properties as a real DOM object.

React populated the idea of Virtual DOM. It is commonly used in PayPal, Apple and Facebook.


Virtual DOM
Is React really fast?
DOM

 Reading and writing is really slow in DOM.


 Changing the whole DOM each time when there is an update will slow down the page.

Virtual DOM

 Has rapid DOM rendering speed because manipulating the virtual DOM is much faster,
because nothing gets drawn onscreen.
 Only the required part of DOM is updated.

Need of React
Why ReactJS?
 Faster and better, thanks to Virtual DOM.
 Can be used on both Client side and server side. - If your app is more of dynamic data, you
can go with client side scripting where you need not request the DOM for every change. -
Static page can be rendered using server side scripts. - A good mixture of both helps maintain
the page safe and efficient.
 Helps to maintain the readability of apps using components which is discussed later. - Can
easily update the state by refering the components.

Need of React
React Features
 Components – easier to maintain larger apps.
 JSX – an optional feature of React that is a JavaScript syntax extension.

Restraints
But Still..
 React only covers view layer of the app, so you still need to choose other technologies to get a
complete tooling set for development.
 React is using inline templating and JSX that might be awkward to some developers.

About JSX
 JSX is an inline markup that looks like HTML that gets transformed to JavaScript.
 It starts with a HTML-like open tag, and ends with the corresponding closing tag.

Example:
const element = <h1>Hello, world!</h1>;

The syntax is intended to be used by preprocessors such as Babel to transform HTML-like


text into standard JavaScript objects.

React with JSX


Why JSX?
React uses JSX instead of the regular JavaScript.

Advantages:
 Faster because it performs optimization while compiling code to JavaScript.
 Type-safe and most of the errors can be caught during compilation.
 Easier and faster to write templates, if you are familiar with HTML.

Quick Fact

It is not mandatory to use JSX with React. But React would


be elegant if JSX is used.
Environment Setup
As ReactJS is really flexible, you can use it in a variety of projects. Either you can create a
new app with it, or you can gradually introduce it into an existing code base so as to avoid a
rewrite.

 You can use the following codepen link to try out the examples

https://codepen.io/FrescoPlay/pen/MpzZOW
 If you are interested to install ReactJS in your system, you can follow the official link
https://facebook.github.io/react/docs/installation.html for the instructions.

Steps to create your own ReactJS pen in codepen:

 Create a New pen in CodePen and make the following changes:


o Goto the settings, change Babel as the JavaScript Preprocessor.
o Add these two ExternalJavaScripts

`https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js`
`https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js`

Building Blocks of ReactJS


A typical ReactJS program constitutes:

 Components
 Elements
 Props
 States
 Functions

Let us now understand about each of these in the next set of cards.

Elements and Components


 Components let you split the UI into independent, reusable pieces, and think about
each piece in isolation.
 Conceptually, components are like JavaScript functions.
 They accept arbitrary inputs (called props) and return React elements describing what
should appear on the screen.
 Elements are the smallest building blocks of React apps.

Props
When you define a component, it can be defined with or without attributes called props. Let
us understand this with an example.

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Jerry" />;
ReactDOM.render(
element,
document.getElementById('root')
);

 You could see, the value 'Jerry' is passed to the prop name in component Welcome.

 Data in props can be accessed using this.props and can be used in render()method


to update dynamic data. In simple words, props are like parameters to the
components.

Let's see a component without a prop value.

function Welcome(props) {
return <h1>Hello, Harry!</h1>;
}

const element = <Welcome />;


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

 Props are immutable. So, the props cannot be changed once it is initialized.

Functions
Like other Javascript frameworks, ReactJS also supports functions.
Pure or Impure?

 In the following code, the function itself updates the props passed. Hence it is impure.

function withdraw(account, amount) {


// Some Code
account = account - amount ;
}
Take a look at the following code snippet. Here the props passed are not affected by the
function. Hence it is pure.

function sum(a, b) {
return a + b;
}

You will find the importance of pure Components in upcoming topics.

Quick Fact

Pure functions are highly recommended in ReactJS


because they do not need frequent DOM updates!
States
State is an object that determines how the component renders and behaves. It is the place
where the data comes from. It allows you to create components that are dynamic and
interactive.

 State can be defined as key-value pair defined in each component.


 It can be -- Initialized with this.state -- Updated on event calls.
 When a component's state data changes, the render function will be called again to re-
render the change in state using this.setState.

States

Let us understand a bit more about State using the following example. As you can notice, as
the user interacts with DOM providing data into the text box, the state is getting updated.

class Component extends React.Component {


constructor(props) {
super(props);
this.state = {text: "Initial text"};
}
update(e)
{
this.setState({text: e.target.value})
}
render() {
return (
<div>
<h1>State Example</h1>
<h2>{this.state.text}</h2>
<input type="text" onChange={this.update.bind(this)}/>
</div>
);
}
}

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

HTML code:

<div id="root">
<!-- This div's content will be managed by React. -->
</div>

Creating an Element
What is an element?
 As we have discussed, they form the basic block of the React app.
 They have the information that is displayed in UI.

Example:
const element = <h1>Hello, world</h1>;

Here <h1>.....</h1> is an element that has the data Hello world.

Here is how we create and use an element in React.

const user = {
name: 'Harry'
};
const myElement = (
<h1>
Hello, {user.name}!
</h1>
);

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

Nested Elements
 You can return only one element at a time in a component
 More than one element can be wrapped up inside a container element
E.g. <div>...</div>
 The following code is an example of Nested elements. You could
see Hello! and Welcome..... are 2 elements nested within the element myMsg.

const myMsg = (
<div>
<h1>Hello!</h1>
<h2>Welcome to the React Tutorial on Fresco Play!</h2>
</div>
);
ReactDOM.render(
myMsg,
document.getElementById('root')
);

Rendering Elements
An element describes what you want to see on the screen.

const myMsg = <h1>Hello, world</h1>;


Rendering an element into the DOM
Let us say, there is a <div> somewhere in your HTML file:

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

 Everything inside root will be managed by React DOM.


 Applications built with just React usually have a single root DOM node.
 To render a React element into a root DOM node, pass both (i.e. element and node) to
ReactDOM.render():

Experssions in JSX
All the javascript expressions can be used in JSX by enclosing the expressions inside curly
braces.

Example
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harry',
lastName: 'Potter'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
ReactDOM.render(
element,
document.getElementById('root')
);

Here return user.firstName + ' ' + user.lastName is an expression and is enclosed


within braces.

Partial rendering
Render only the updates
When an update is performed in the state of the element, only that particular element is re-
rendered. Run the following code and inspect the elements to understand how only the
element is updated.

Example

function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(
element,
document.getElementById('root')
);
}

setInterval(tick, 1000);

It calls ReactDOM.render() every second from a setInterval() and updateds the UI .

Creating Components
The simplest way to define a component is to write a JavaScript function:

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

This accepts a single "props" object argument and returns a React element.

You can also use an ES6 class to define a component.

class Welcome extends React.Component {


render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

The above two components are equivalent from React's point of view.

Composing Components
 They are the Components that refer to other components in their output.
 This lets us use the same component definition with different props value.

For example, we can create a component App that refers another component Welcome in


output:

function Welcome(props) {
return <h1>Hello {props.name}</h1>;
}

function App() {
return (
<div>
<Welcome name="Harry" />
<Welcome name="Jerry" />
<Welcome name="Jini" />
</div>
);
}

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

Components must return a single root element. This is why we added a <div> to contain all
the <Welcome /> elements.

More on Components
The core of React js programming is React components. Just like everything in HTML is an element,
everything in React is a component. In this video, we'll break down how a component works.
Larger Components
You can break larger components into smaller reusable ones in React. For example, consider
this Comment component:

function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}

It accepts author (an object), text (a string), and date (a date) as props, and describes a


comment on a social media website.

This component can be tricky to change because of all the nesting, and is also hard to reuse
individual parts of it. Lets see how this larger component can be split into smaller one.

Extracting Components
Let us extract the Avatar component from the previous example:

function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
);
}

The Avatar does not need to know that it is being rendered inside a Comment. This is why we
have given its prop a more generic name: user rather than author.

Event Handling in React


Event handling
 Similiar to event handling in DOM.
 Uses camelCase syntax, instead of lowercase syntax.
 In JSX, event is passed as an event handler, rather than a String.

Let us take a look at how the onclick event handler of a button differs in HTML and React:

HTML
<button onclick="activateLasers()">
Activate Lasers
</button>

React
<button onClick={activateLasers}>
Activate Lasers
</button>

Event Handling in React


HTML Vs React
 Cannot return false to prevent default behavior in React as of in HTML.
 preventDefault() should be called explicitly in React.
HTML
<a href="#" onclick="console.log('The link was clicked.');
return false"> Click me </a>

React

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.'); }
return ( <a href="#" onClick={handleClick}> Click me </a> );
}

Here Preventdefault() was called to print a message in console rather than openning a


URL.

What are Life Cycle Events?


Lifecycle methods are special methods with which you can perform certain actions that you
require at particular instance i.e. when the component first renders or when the component
gets updated with new data, etc.

Methods prefixed with will are called right before some conditions happens, and methods
prefixed with did are called right after something happens.

Why Life Cycle Events:

 In any app with many components, it is important to release the resources once a
component is destroyed
 It can be achieved with the help Life Cycle Events
 We have some special functions to do this resource management tasks and are
explained in the next set of cards

Mounting,Updating and Unmounting


Mounting is creating new instance of a component and inserting into the DOM.

constructor()
componentWillMount()
render()
componentDidMount()
Updating is re-rendering the Component.

componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()

Unmounting is when a component is being removed from the DOM

Method that is called when :

componentWillUnmount()

Keys
 Conceptually keys are like bookmarks which will keep track of list elements
 Useful when working with dynamically created components or when your list is altered
 Will keep your components uniquely identified after the change
 Uses the key values to keep track of each elements whenever elements are added or
removed or order of the elements are changed

How can you add Keys to list?

 using key keyword

Example:

<li key={index}> {props.value} </li>

Ref

 ref is like id to a particular element in a form.


 Makes it possible to store a reference to a particular element or component returned by
the render() function
 To use reference, place the ref attribute within an element or a component with a name
 Inside of the function, use this.refs to use that particular element or component.

Example

class CustomTextInput extends React.Component {


constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}

focus() {
// Explicitly focus the text input using the raw DOM API
this.refs.textInput.focus();
}

render() {
// Use the ref callback to store a reference to the text input DOM
// element in an instance field (for example, this.textInput).
return (
<div>
<input
type="text"
ref="textInput" /><br/><br/>
<input
type="text"
/><br/><br/>

<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
ReactDOM.render(
<CustomTextInput />,
document.getElementById('root')
);
This example uses a ref attribute for a particular textbox and that ref is used in the
function focus() to refer the corresponding textbox.

Quick Fact

 All Components must act like pure functions with


respect to their props.
 If not pure, it means it can return different results for
the same input.
 Virtual DOM cannot help us and you need a DOM
update.
 This affects the performance.
Quick Fact

 React uses special built-in typechecking functionality.


 To use typechecking on the props for a component,
you can assign the special propTypes property .
 This will help you track all props in your app.
 Useful to all developers working on the same project.

Quick Fact

 You should always try to keep app's logic


inside render() method.
 Use of state and props should be reduced, so that
the code will be clean.
 You should always make State as simple as
possible.
Quick Fact
It is always a good practice to use single component per
functionality.

ReactJS Course Summary


In this course you have learnt:

 The need for ReactJS


 Basic concepts like components, props and states
 Using Composite components
 Handling events and the usage of lifecycle events
 Functions of keys and Ref
 And finally some best practices while coding in ReactJS

Quiz :

ReactJS - Interlace your Interface

1. Exciting feature of ReactJS is ________Virtual DOM


2. React considers everything as _______Components
3. React covers __________ layer of the app--View
4. In React, a state can be defined as a---Key-value
5. JSX is typesafe---True
6. JSX is faster because it performs ____________ while compiling code to JavaScript----optimization
7. In JSX most of the errors can be caught during---compilation
8. Components increases _____________.Reusablity
9. can be done while more than one element needs to be returned from a component---wrapping
10. A component may return any number of elements.--False
11. A component cannot directly refer to any other component in its output---False
12. What is the smallest building block of ReactJS?--->Elements
13. Two building blocks of ReactJS are--->Kyes&List
14. Props are mutable---True
15. Arbitrary inputs of components are called---Props
16. Function that does not change its results for the same set of inputs are called ---Pure Function
17. In JSX ______________ is passed as event handlers---actions(wrong)strings
18. We can declare special methods on the component class to run some code when a component mounts
and unmounts.---true
19. Event handling in React is more similar to Event handling in DOM---True
20. How can we prevent default behavior in React?---preventDefault()
21. An altered component may be uniquely idemtified with the help of ref--False
22. We can go for keys when there is possibility that our user could change the data.---keys
23. ref is used to refer a element / component returned by---render()
24. React supports all the syntax of---ES6(wrong)
25. When a component state data changes, we can use--this.setState
26. State can be initialized when code is loaded or state can be set on event changes---True
27. Which of the following needs to be updated to achieve dynamic UI updates?---state
28. To Prevent firing of the component's lifecycle methods you can use null from render menthod--True
29. Components cannot refer to other components in their output--False
30. React keeps track of what items have changed, been added, or been removed from a list using--state
31. In React state can be accessed using---this.state()
32. If you create a element , you can't change its--Children
33. Batching of multiple setState() calls in single update is possible--True
34. Invoked once, only on the client, after rendering occurs---- componentDidMount()
35. We can go for keys when there is possibility that our user could change the data----kyes
36. React uses _____________ syntax--->>camelcase
37. Keys used within arrays should be globally unique---False
38. React merges the object you provide into the current state using---this.setState()
39. Which lifecycle event is invoked before rendering and when new props or state are being received----
componentDidUpdate()
40. React is mainly for building---user interface
41. Which of the following is used to pass the data from parent to child---props
42. React covers---view
43. In JSX ______________ is passed as event handlers.---events

You might also like