React

March 15, 2018 | Author: Shyam Santhosh | Category: Web Development, Software Engineering, Computing, Technology, Software
Share Embed Donate


Short Description

Introduction to reactJS...

Description

Introduction to REACT

1. INTRODUCTION 1.1 WHAT IS REACT

In computing, React (sometimes

styled React.js or ReactJS)

is

an open-

source JavaScript library for building user interfaces. It is maintained by Facebook, Instagram and a community of individual developers and corporations.As of July 2017, according to JavaScript analytics service Libscore, websites such

as Airbnb, Buffer, Bleacher

Report, Feedly, HelloSign, Imgur, Netflix, SeatGeekand

others use React. React allows developers to create large web-applications that use data that can change over time, without reloading the page. It aims primarily to provide speed, simplicity and scalability. React processes only user interfaces in applications. This corresponds to View in the Model-View-Controller (MVC) template, and can be used in combination with other JavaScript libraries or frameworks in MVC, such as AngularJS. 1.1.1Features While the React’s brothers (Angular, Ember, Backbone) are dubbed as clientside MVCframeworks, this guy is different. His creators call him the ‘V’ of MVC. In other words. he entirely focuses on ‘View’ which describes the User Interaction part. React is the fastest of the bunch. He carefully notes down the differences in his in-memory cache and use these differences to update the DOM in browser, which is what gives him the boost. This is the Virtual DOM feature. Other notable features include One way dataflow and JSX (the react components are basically JSX).

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 1

Introduction to REACT 1.1.2 History React was created by Jordan Walke, a software engineer at Facebook. He was influenced by XHP, an HTML component framework for PHP. It was first deployed on Facebook's newsfeed in 2011 and later on Instagram.com in 2012.It was open-sourced at JSConf

US

in

May

2013. React

Native,

which

enables

native Android, iOS,

and UWP development with React, was announced at Facebook's React.js Conf in February 2015 and open-sourced in March 2015. On April 18, 2017, Facebook announced React Fiber, a new core algorithm of React framework library for building user interfaces. React Fiber will become the foundation of any future improvements and feature development of the React framework.

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 2

Introduction to REACT

2. WHY REACT? 

V(view) of MVC - Solution of View in MVC



Virtual DOM - Reactjs use the concept of virtual DOM which helps in the performance



Unidirectional Data Flow - Compare to the 2 way data binding. Reactjs use the concept of Unidirectional data flow which improve the over all performance.



UI Components - Reusable and interactive components



SEO Friendly - Components are client side as well as server side render hence they are SEO friendly and no 3rd party plugin required



Coding is simpler because of JSX



Reactjs own debugger



React Native is going to be next big thing



Big minds are backing Reactjs

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 3

Introduction to REACT

3. 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 to 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.

3.1 React Advantages



React uses virtual DOM which is JavaScript object. This will improve apps performance since JavaScript virtual DOM is faster than the regular DOM.



React can be used on client and server side.



Component and Data patterns improve readability which helps to maintain larger apps.



React can be used with other frameworks.

3.2 React Limitations 

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. This can seem awkward to some developers.

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 4

Introduction to REACT

4. ReactJS - Environment Setup INSTALLING NODE AND NPM Getting React up and running is not as simple as downloading one large piece of software. You will need to install many, smaller software packages. The first thing to install is a good installer! You need a way to download and install software packages easily, without having to worry about dependencies. In other words, you need a good package manager. We'll be using a popular package manager named npm. npm is a great way to download, install, and keep track of JavaScript software. You can install npm by installing Node.js. Node.js is an environment for developing serverside applications. When you install Node.js, npm will install automatically. Ctrl-click here to navigate to the Node.js homepage in a new tab. You should see links to download Node.js. Click on the download link of your choice. Follow the subsequent instructions to install Node.js and npm. If you've already installed Node.js, that's okay, do it anyway. Congratulations! You've just installed some incredibly powerful software! HOW NPM IS DIFFERENT When you install software, you may be used to something like this: you install what you need, it sits there on your computer, and you can use it whenever you want. You can do that with npm! But there's a different, better way: install what you need, over and over again, every time that you need it. Download and install React every time that you make a React app. That sounds much worse! Here's why it's actually better: First, npm makes installation extremely easy. Installing software over and over sounds like a headache, but it really isn't. We'll walk through how soon! Second, npm modules ("modules" are another name for software that you download via npm) are usually small. There are countless modules for different specific purposes. Instead of

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 5

Introduction to REACT starting your app with a giant framework that includes tons of code you don't need, you can install only modules that you will actually use! This helps keep your code quick, easy to navigate, and not vulnerable to dependencies that you don't understand. IN CONCLUSION: Starting now, every step in this article series will be a step that you have to

take every

time

you

make

a

new

React

app.

You

don't

have

to

install Node.js and npm anymore, but you should start from here for every new React project that you make. Step 1 - Install Global Packages You will need to install several packages for this setup. We will need some of the babel plugins so let's first install babel by running the following code in command prompt window. C:\Users\username>npm install -g babel C:\Users\username>npm install -g babel-cli

Step 2 - Create Root Folder The root folder will be named reactApp and we will place it on Desktop. After the folder is created we need to open it and create empty package.json file inside by running npm init from the command prompt and follow the instructions. C:\Users\username\Desktop>mkdir reactApp C:\Users\username\Desktop\reactApp>npm init

Step 3 - Add Dependencies and plugins We will use webpack bundler in these tutorials so let's install webpack and webpack-devserver. C:\Users\username>npm install webpack --save C:\Users\username>npm install webpack-dev-server --save Since we want to use React, we need to install it first. The --save command will add these packages to package.json file.

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 6

Introduction to REACT

C:\Users\username\Desktop\reactApp>npm install react --save C:\Users\username\Desktop\reactApp>npm install react-dom --save We already mentioned that we will need some babel plugins so let's install it too. C:\Users\username\Desktop\reactApp>npm install babel-core C:\Users\username\Desktop\reactApp>npm install babel-loader C:\Users\username\Desktop\reactApp>npm install babel-preset-react C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015

Step 4 - Create files Let's create several files that we need. You can add it manually or you can use command prompt. C:\Users\username\Desktop\reactApp>touch index.html C:\Users\username\Desktop\reactApp>touch App.jsx C:\Users\username\Desktop\reactApp>touch main.js C:\Users\username\Desktop\reactApp>touch webpack.config.js

Step 5 - Set Compiler, Server and Loaders Open webpack-config.js file and add the code below. We are setting webpack entry point to be main.js. Output path is the place where bundled app will be served. We are also setting development server to 8080 port. You can choose any port you want. And lastly, we are setting babel loaders to search for js files and use es2015 and react presets that we installed before. webpack.config.js var config = { entry: './main.js',

output: { path:'./', filename: 'index.js',

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 7

Introduction to REACT

},

devServer: { inline: true, port: 8080 },

module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel',

query: { presets: ['es2015', 'react'] } } ] } }

module.exports = config; Open the package.json and delete "test" "echo \"Error: no test specified\" && exit 1" inside "scripts" object. We are deleting this line since we will not do any testing in this tutorials. Let's add the start command instead. "start": "webpack-dev-server --hot" Now we can use npm start command to start the server. --hot command will add live reload after something is changed inside our files so we don't need to refresh the browser every time we change our code. Step 6 - index.html

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 8

Introduction to REACT This is just regular HTML. We are setting div id = "app" as a root element for our app and adding index.js script which is our bundled app file.

React App





Step 7 - App.jsx and main.js This is the first react component. We will explain React components in depth in one of our later tutorials. This component will render Hello World!!!. App.jsx import React from 'react';

class App extends React.Component { render() { DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 9

Introduction to REACT

return ( Hello World!!! ); } }

export default App; We need to import this component and render it to our root App element so we can see it in browser.

main.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx';

ReactDOM.render(, document.getElementById('app'));

Step 8 - Running the Server The setup is finished and we can start the server by running: C:\Users\username\Desktop\reactApp>npm start It will show you the port we need to open in browser, in our case http://localhost:8080/. After we open it we will see the following output:

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 10

Introduction to REACT

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 11

Introduction to REACT

5. CORE CONCEPTS 1. JSX 2. VIRTUAL DOM 3. UNIDIRECTIONAL DATAFLOW 4. COMPONENTS 5.1 React-JSX React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, but there are some pros that comes with it. 

JSX is faster because it performs optimization while compiling code to JavaScript.



It is also type-safe and most of the errors can be caught during compilation.



JSX makes it easier and faster to write templates if you are familiar with HTML.

Using JSX JSX looks like regular HTML in most cases. We already used it in environment setup tutorial. Look at the code from App.jsx where we are returning div. App.jsx import React from 'react';

class App extends React.Component { render() { return ( Hello World!!! );

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 12

Introduction to REACT

} }

export default App; Even though it's similar to HTML, there are a couple of things you need to keep in mind when working with JSX. Attributes You can use your own custom attributes in addition to regular HTML properties and attributes. When you want to add custom attribute, you need to use data- prefix. In example below we added data-myattribute as an attribute of p element. import React from 'react';

class App extends React.Component { render() { return ( Header Content This is the content!!! ); } }

export default App; DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 13

Introduction to REACT

JavaScript Expressions JavaScript expressions can be used inside of JSX. You just need to wrap it with curly brackets {}. Example below will render 2. import React from 'react';

class App extends React.Component { render() { return ( {1+1} ); } }

export default App;

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 14

Introduction to REACT

You can not

use if

else statements

inside JSX but

you can use conditional

(ternary) expressions instead. In example below variable i equals to 1 so the browser will render true, if we change it to some other value it will render false. import React from 'react';

class App extends React.Component { render() {

var i = 1;

return ( {i == 1 ? 'True!' : 'False'} ); } } DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 15

Introduction to REACT

export default App;

Styling React recommends using inline styles. When you want to set inline styles, you need to use camelCase syntax. React will also automatically append px after the number value on specific elements. You can see below how to add myStyle inline to h1 element. import React from 'react';

class App extends React.Component { render() {

var myStyle = { fontSize: 100, color: '#FF0000' }

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 16

Introduction to REACT

return ( Header ); } }

export default App;

Comments When writing comments you need to put curly brackets {} when you want to write comment within children section of a tag. It is good practice to always use {} when writing comments since you want to be consistent when writing the app. import React from 'react';

class App extends React.Component {

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 17

Introduction to REACT

render() { return ( Header {//End of the line Comment...} {/*Multi line comment...*/} ); } }

export default App; Naming Convention HTML tags are always using lowercase tag names, while React components starts with Uppercase.

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 18

Introduction to REACT 5.2The Virtual DOM In React, for every DOM object, there is a corresponding "virtual DOM object." A virtual DOM object is a representation of a DOM object, like a lightweight copy. A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing's power to directly change what's on the screen. Manipulating the DOM is slow. Manipulating the virtual DOM is much faster, because nothing gets drawn onscreen. Think of manipulating the virtual DOM as editing a blueprint, as opposed to moving rooms in an actual house. How it helps When you render a JSX element, every single virtual DOM object gets updated. This sounds incredibly inefficient, but the cost is insignificant because the virtual DOM can update so quickly. Once the virtual DOM has updated, then React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update. By comparing the new virtual DOM with a pre-update version, React figures out exactly which virtual DOM objects have changed. This process is called "diffing." Once React knows which virtual DOM objects have changed, then React updates those objects, and only those objects, on the real DOM. In our example from earlier, React would be smart enough to rebuild your one checked-off list-item, and leave the rest of your list alone. This makes a big difference! React can update only the necessary parts of the DOM. React's reputation for performance comes largely from this innovation. In summary, here's what happens when you try to update the DOM in React: The entire virtual DOM gets updated. The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed. The changed objects, and the changed objects only, get updated on the realDOM. Changes on the real DOM cause the screen to change. DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 19

Introduction to REACT Traditional DOM

React Virtual DOM

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 20

Introduction to REACT 5.3 UNIDIRECTIONAL DATAFLOW As compare to other MVC frameworks/Library Reactjs use the concept of unidirectional data flow. - In Reactjs application the data flow from the parent to the children component by the state and the props. - Only one parent is responsible to update the states and passing the value to the children components via props. - setState is used to update/refresh the UI when the state change and the value can be pass to the children component by the this.props To fully understand the benefits of unidirectional data flow, you must first understand the inherent issues with the alternative. The alternative, of course, is bidirectional data flow. This data paradigm typically manifests itself as some sort of model binding. For many years, application architecture has revolved around the model-view-controller, or MVC, pattern. In this pattern, a model is responsible to storing and retrieving application data. The view is the presentational piece of the application–what the end-user sees. The controller is responsible for transforming data from a model so that it can be presented via the view.

Typical Model-View-Controller data flow For a long time, this pattern was exactly what we as developers needed. It offered separation of concerns. The view shouldn’t be concerned with where the data came from, and vice versa. The model shouldn’t concern itself with how the data is presented. This pattern works great for simple applications, but quickly starts to break down as applications become more complex. Many applications rely on user interaction to drive data and application state, which puts greater responsibility on the controller. It has to both maintain application state, and act DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 21

Introduction to REACT as a mediator between the view and model. This complexity led us to model-binding, which allowed developers to auto-bind user interface changes to changes in the data model, and vice versa. Herein lies the problem: Application data and state are being manipulated from two sources and more or less bypassing the controller. The current state of the application is no longer predictable.

Data flow when using model-binding Unidirectional data flow, on the other hand, provides predictable application state. In a typical unidirectional application architecture, changes in an application view layer trigger an action within the data layer. Those changes are then propagated back to the view. It is important to note here that the view does not directly affect the application data.

Unidirectional data flow

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 22

Introduction to REACT

5.4 COMPONENTS Everything in reactjs is components. The core building blocks of React application is components only. Components interact with each other and maintain the state too. In Reactjs whole application is need to be break into the component only.

COMPONENT LIFE CYCLE 

componentWillMount is executed before rendering, on both server and client side.



componentDidMount is executed after first render only on the client side. This is where AJAX requests and DOM or state updates should occur. This method is also used for integration with other JavaScript frameworks and any functions with delayed execution like setTimeoutor setInterval. We are using it to update the state so we can trigger the other lifecycle methods.



componentWillReceiveProps is invoked as soon as the props are updated before another render is called. We triggered it from setNewNumber when we updated the state.



shouldComponentUpdate should return true or false value. This will determine if component will be updated or not. This is set to trueby default. If you are sure that component doesn't need to render after state or props are updated, you can return false value.



componentWillUpdate is called just before rendering.

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 23

Introduction to REACT 

componentDidUpdate is called just after rendering.



componentWillUnmount is called after the component is unmounted from the dom. We are unmounting our component in main.js.

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 24

Introduction to REACT

6.CONCLUSION

ReactJS is a library that generates the view layer of an application based on its state. ReactJS applications are built from React Components - independent resusable components that describe how the UI should look based on their own state and properties. Somany websites are using react, React one of the most demanded career now. React is a performant, view focused, component based library. In itself, it is not sufficient to build a whole SPA. There are many approaches on how to use React with other frameworks (Backbone and even Angular). The preferred way of using React (championed by Facebook) is to follow the Flux architecture. There isn’t currently available mature open source implementation of the Flux architecture, which would provide ecosystem of features that are needed to effectively develop SPA as of January 2015. Because of these reasons, React isn’t a sensible choice when developing standard web applications. In special cases it can be employed as a part of an Angular application to handle a high performance load when displaying big data sets although Angular (1.3) provided possibility to use one time data binding (:: expression) which can be employed in those situations.

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 25

Introduction to REACT

7. REFERENCES 1. https://www.google.co.in 2. https://facebook.github.io/react 3. https://www.tutorialspoint.com/reactjs 4. https://www.edx.org/ 5. http://opensourceforu.com/?s=reactJS 6. https://scotch.io/

DEPARTMENT OF COMPUTER APPLICATION, CUCEK

Page 26

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF