Reactjs - Interlace Your Interface Introduction To Reactjs: What Is Exciting Here?
Reactjs - Interlace Your Interface Introduction To Reactjs: What Is Exciting Here?
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.
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>;
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
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.
`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`
Components
Elements
Props
States
Functions
Let us now understand about each of these in the next set of cards.
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.
function Welcome(props) {
return <h1>Hello, Harry!</h1>;
}
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 sum(a, b) {
return a + b;
}
Quick Fact
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.
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>;
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.
<div id="root"></div>
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')
);
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);
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.
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.
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>
);
}
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.
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>
React
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.'); }
return ( <a href="#" onClick={handleClick}> Click me </a> );
}
Methods prefixed with will are called right before some conditions happens, and methods
prefixed with did are called right after something happens.
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
constructor()
componentWillMount()
render()
componentDidMount()
Updating is re-rendering the Component.
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
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
using key keyword
Example:
Ref
Example
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
Quick Fact
Quiz :