ReactJS – Icons

ReactJS – Icons ”; Previous Next Web Icons are important assets in a web application. Developer use it extensively in multiple places to better visualize the context. For example, a menu can be made easily identifiable with a menu icon. Web icons has a long history and have multiple implementation throughout its long history. Initially, icons are simple images in standard sizes, like 24×24, 32×32, 48×48, etc., Later, multiple icons are designed as single image called icon sprint as used in a website through CSS positioning property. Then, fonts are used to hold multiple icons and used through CSS font-family property. Latest in the list is the SVG icons. SVG icons are designed and saved in SVG format and used in the website either through img tag or inline SVG option. React provides a community based icon library called React icons, which provides extensive set of icons from different icon library. Let us learn how to use react icon library in this chapter. React icon (React-icon) library React icon library collects thousand of icons from different vendor and wrap it as React component. Developer can use it as simple as including a react component to use a particular icon in their project. A small list of icon set provided by React icons is as follows − Bootstrap icons Material design icons Font Awesome Devicons Boxicons Ant Design icons Github Octicons icons VS Code icons React icons provides much more set of icons and we can check all the icons at their website (https://react-icons.github.io/react-icons/) Installing react icons library Installing React icons library in a web application is as simple as installing a package using npm as shown below − npm install react-icons –save Using react icon component Each icon in the library will have a relevant react component. Developer can find the icon component they need from the React icon library website and use it in their web application. Let us see how to use a calender icon from material design set from react icon library. The name of the calendar icon component from material design is MdCalendarToday. The package of material design icon set is react-icons/md. Developer need to import the package and should use the component in the relevant place as shown below − import { MdCalendarToday } from “react-icons/md”; // … // … class SimpleIcon extends React.Component { render() { return <div>This icons <MdCalendarToday /> is calendar icon imported from react icon library</div> } } Developer can change the color and size of the icon through CSS. class SimpleIcon extends React.Component { render() { return <div>This icons <MdCalendarToday style={{backgroundColor: “red”, size: “24px”}}/> is calendar icon imported from react icon library</div> } } Applying react icon library Let us learn the concept of forwardRef by developing an application. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, install the react icon library as shown below − npm install react-icons –save Next, open App.css (src/App.css) and remove all the CSS classes. // remove the css Next, create a simple component, SimpleIcon (src/Components/SimpleIcon.js) as shown below − import React from “react”; import { MdCalendarToday } from “react-icons/md”; class SimpleIcon extends React.Component { render() { return <div>This icons <MdCalendarToday style={{ color: “red”, size: “24px” }} /> is calendar icon imported from react icon library</div> } } export default SimpleIcon Here, Imported react-icons/md library. Used MdCalendarToday component to render the calendar icon. Used inline style to change the color and size of the icon. Next, open App component (src/App.js) and update the content with SimpleIcon component as shown below − import ”./App.css” import React from ”react”; import SimpleIcon from ”./Components/SimpleIcon” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleIcon /> </div> </div> </div> ); } export default App; Here, Imported the SimpleIcon component. Used SimpleIcon component to render the calender icon. Finally, open the application in the browser. The calendar icon will be rendered as shown below − Summary React icon library helps developer by collecting all kind of icons from different sources and put it in one place and provides it in a simple and easy way. Print Page Previous Next Advertisements ”;

ReactJS – CLI Commands

ReactJS – CLI Commands ”; Previous Next React has its own command-line interface (CLI) commands. However, these CLI commands are currently only used to create a passable version of a react application using the command line. This will contain a default template as its design, so all the react application created this way will have great consistency as they all have same structure. Basic CLI Commands in React Let us learn the basic commands available in Create React App command line application in this chapter. Creating a new application Create React App provides multiple ways to create React application. Using npx script. npx create-react-app <react-app-name> npx create-react-app hello-react-app Using npm package manager. npm init react-app <react-app-name> npm init react-app hello-react-app Using yarn package manager. yarn init react-app <react-app-name> yarn init react-app hello-react-app Selecting a template Create React App creates React application using default template. Template refers the initial code with certain build-in functionality. There are hundreds of template with many advanced features are available in npm package server. Create React App allows the users to select the template through -template command line switch. create-react-app my-app –template typescript Above command will create react app using cra-template-typescript package from npm server. Installing a dependency React dependency package can be installed using normal npm or yarn package command as React uses the project structure recommended by npm and yarn. Using npm package manager. npm install –save react-router-dom Using yarn package manager. yarn add react-router-dom Running the application React application can be started using npm or yarn command depending on the package manager used in the project. Using npm package manager. npm start Using yarn package manager. yarn start To run the application in secure mode (HTTPS), set an environment variable, HTTPS and set it to true before starting the application. For example, in windows command prompt (cmd.exe), the below command set HTTPS and starts the application is HTTPS mode. set HTTPS=true && npm start Print Page Previous Next Advertisements ”;

ReactJS – Custom Hooks

ReactJS – Custom Hooks ”; Previous Next Hooks are integral part of a function component. They can used to enhance the feature of the function component. React provides few build-in hooks. Even though build-in hooks are powerful and can do any functionality, specialized hooks are necessary and in high demand. React understands this need of the developer and allows to create new custom hooks through existing hooks. Developer can extract a special functionality from the function component and can create it as a separate hook, which can be used in any function component. Let us learn how to create custom hooks in this chapter. Create a custom hook Let use create a new react function component with infinite scroll feature and then extract the infinite functionality from the function component and create a custom hook. Once the custom hook is created, we will try to change the original function component to use our custom hook. Implement Infinite scroll functionality The basic functionality of the component is to show a dummy list of todo item simply by generating it. As the user scrolls, the component will generate a new set of dummy todo list and append it to the existing list. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, create a react component, TodoList under component folder (src/components/TodoList.js) function TodoList() { return <div>Todo List</div> } export default TodoList Next, update the root component, App.js to use the newly created TodoList component. import TodoList from ”./components/TodoList”; function App() { return ( <div style={{ padding: “5px”}}> <TodoList /> </div> ); } export default App; Next, create a count state variable to maintain the number of todo items to e generated. const [count, setCount] = useState(100) Here, The initial number of items to be generated is 100 count is the state variable used to maintain the number to todo items Next, create a data array to maintain the dummy generated todo items and preserve the reference using useMemo hook. React.useMemo(() => { for (let i = 1; i <= count; i++) { data.push({ id: i, todo: “Todo Item ” + i.toString() }) } }, [count]); Here, Used useMemo to restrict the generation of todo items on every render. Used count as a dependency to regenerate the todo items when the count changes Next, attach a handler to the scroll event and update the count of the todo item to generated when the user moved to the end of the page. React.useEffect(() => { function handleScroll() { const isBottom = window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight; if (isBottom) { setCount(count + 100) } } window.addEventListener(“scroll”, handleScroll); return () => { window.removeEventListener(“scroll”, handleScroll); }; }, []) Here we have, Used useEffect hook to make sure the DOM is ready to attach the event. Attached an event handler, scrollHandler for scroll event. Removed the event handler when the component is unmounted from the application Found that the user hits the bottom of the page using DOM properties in the scroll event handler. Once the user hit the bottom of the page, the count is incremented by 100 Once the count state variable is changed, the component gets rerendered and more todo item are loaded. Finally, render the todo items as shown below − <div> <p>List of Todo list</p> <ul> {data && data.map((item) => <li key={item.id}>{item.todo}</li> )} </ul> </div> The complete source code of the component is as follows − import React, { useState } from “react” function TodoList() { const [count, setCount] = useState(100) let data = [] React.useMemo(() => { for (let i = 1; i <= count; i++) { data.push({ id: i, todo: “Todo Item ” + i.toString() }) } }, [count]); React.useEffect(() => { function handleScroll() { const isBottom = window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight; if (isBottom) { setCount(count + 100) } } window.addEventListener(“scroll”, handleScroll); return () => { window.removeEventListener(“scroll”, handleScroll); }; }, []) return ( <div> <p>List of Todo list</p> <ul> {data && data.map((item) => <li key={item.id}>{item.todo}</li> )} </ul> </div> ) } export default TodoList Next, Open the browser and run the application. The application will append new todo item once the user hits the end of the page and goes on infinitely as shown below − Implementing useInfiniteScroll hook Next, let us try to create new custom hook by extracting the logic from the existing component and then use it in a separate component. Create a new custom hook, useInfiniteScroll (src/Hooks/useInfiniteScroll.js) as shown below import React from “react”; export default function useInfiniteScroll(loadDataFn) { const [bottom, setBottom] = React.useState(false); React.useEffect(() => { window.addEventListener(“scroll”, handleScroll); return () => { window.removeEventListener(“scroll”, handleScroll); }; }, []); React.useEffect(() => { if (!bottom) return; loadDataFn(); }, [bottom]); function handleScroll() { if (window.innerHeight + document.documentElement.scrollTop != document.documentElement.offsetHeight) { return; } setBottom(true) } return [bottom, setBottom]; } Here we have, Used use keyword to name the custom hook. This is the general practice to start the name of the custom hook with use keyword and it is also a hint for the react to know that the function is a custom hook Used a state variable, bottom to know whether the user hits the bottom of the page. Used useEffect to register the scroll event once the DOM is available Used a generic function, loadDataFn to be supplied during the creation of hook in the component. This will enable to create custom logic for loading the data. Used DOM properties in the scroll event handler to track the user scroll position. when the user hits the bottom of the page, the bottom state variable is

ReactJS – Portals

ReactJS – Portals ”; Previous Next Portals provides a way for a component to render its children into a DOM node outside its own DOM hierarchy. Portal can be used in model dialog, popups, tooltip, etc., where the parent (the rendering component) and child DOM node (model dialogs) are preferred to be rendered in different DOM node. Let us learn how portal works and how to apply it in our application in this chapter. Concept and usage of portals Let us consider that we have two DOM node in the main document as shown below − <div id=”root”></div> <div id=”modalRoot”></div> Here, root DOM node will be attached with main react component. modalRoot will be used by the react application whenever it needs to show a modal dialog by attaching the modal dialog into the modelRoot DOM node instead of rendering the model dialog inside its own DOM element. This will help to separate the modal dialog from the actual application. The separation of modal dialog from its parent DOM element will preserve it from the styling of its parent DOM element. The styling can be applied separately as modal dialogs, tooltips, etc., differs from its parent with regard to styling. React provides a special method createPortal in ReactDOM package to create a portal. The signature of the method is as follows − ReactDOM.createPortal(child, container) Here, child is the model dialogs, tooltips, etc., rendered by the parent component. render() { return ReactDOM.createPortal( this.props.children, // modal dialog / tooltips domNode // dom outside the component ); } container is the DOM element outside the parent DOM node (domNode in above example) Applying portals Let us create a new react application to learn how to apply portals in this section. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, open App.css (src/App.css) and remove all CSS classes and include CSS for modal dialogs. .modal { position: absolute; top: 0; bottom: 0; left: 0; right: 0; display: grid; justify-content: center; align-items: center; background-color: rgba(0,0,0,0.2); } .modalContent { padding: 20px; background-color: #fff; border-radius: 2px; display: inline-block; min-height: 300px; margin: 1rem; position: relative; min-width: 300px; box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23); justify-self: center; } Next, open index.html (public/index.html) and add a DOM node to support portals <!DOCTYPE html> <html lang=”en”> <head> <link rel=”icon” href=”%PUBLIC_URL%/favicon.ico” /> <link rel=”apple-touch-icon” href=”%PUBLIC_URL%/logo192.png” /> <link rel=”manifest” href=”%PUBLIC_URL%/manifest.json” /> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div style=”padding: 10px;”> <div id=”root”></div> </div> <div id=”modalRoot”></div> </body> </html> Next, create a simple component, SimplePortal (src/Components/SimplePortal.js) and render a modal dialog as shown below − import React from “react”; import PortalReactDOM from ”react-dom” const modalRoot = document.getElementById(”modalRoot”) class SimplePortal extends React.Component { constructor(props) { super(props); } render() { return PortalReactDOM.createPortal( <div className=”modal” onClick={this.props.onClose} > <div className=”modalContent”> {this.props.children} <hr /> <button onClick={this.props.onClose}>Close</button> </div> </div>, modalRoot, ) } } export default SimplePortal; Here, createPortal to create a new portal and renders a modal dialog. Content of the modal dialog are retrieved from children of the component through this.props.children close button actions are handled through props and will be handled by the parent component. Next, open App component (src/App.js), and use SimplePortal component as shown below − import ”./App.css” import React from ”react”; import SimplePortal from ”./Components/SimplePortal” class App extends React.Component { constructor(props) { super(props); this.state = { modal: false } } handleOpenModal = () => this.setState({ modal: true }) handleCloseModal = () => this.setState({ modal: false }) render() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <div><p>Main App</p></div> <div> <button onClick={this.handleOpenModal}> Show Modal </button> { this.state.modal ? ( <SimplePortal onClose={this.handleCloseModal}> Hi, I am the modal dialog created using portal. </SimplePortal> ) : null} </div> </div> </div> </div> ); } } export default App; Here, Imported SimplePortal component Added a button to open the modal dialog Created a handler to open the modal dialog Created a handler to close the modal dialog and passed it to SimplePortal component through onClose props. Finally, open the application in the browser and check the final result. Summary React portal provides an easy way to access and handle DOM outside the component. It enables the event bubbling across the different DOM nodes without any extra effort. Print Page Previous Next Advertisements ”;

ReactJS – Quick Guide

Reactjs – Quick Guide ”; Previous Next ReactJS – Introduction ReactJS is a free and open-source front-end JavaScript library which is used to develop various interactive user-interfaces. It is a simple, feature rich and component based UI library. When we say component based, we mean that React develops applications by creating various reusable and independent codes. This UI library is, thus, widely used in web development. ReactJS can be used to develop small applications as well as big, complex applications. ReactJS provides minimal and solid feature set to kick-start a web application. React community compliments React library by providing large set of ready-made components to develop web application in a record time. React community also provides advanced concept like state management, routing, etc., on top of the React library. React versions Reactjs library was founded by Jordan Walke, a software engineer at Facebook in 2011. Then the initial version, 0.3.0 of React is released on May, 2013 and the latest version, 17.0.1 is released on October, 2020. The major version introduces breaking changes and the minor version introduces new feature without breaking the existing functionality. Bug fixes are released as and when necessary. React follows the Semantic Versioning (semver) principle. What is the need for ReactJS? Even though there are various libraries that provide a medium to develop user-interfaces, ReactJS still stands tall in terms of popularity. Here”s why − Component Based − ReactJS makes use of multiple components to build an application. These components are independent and have their own logic which makes them reusable throughout the development process. This will drastically reduce the application”s development time. Better and Faster Performance − ReactJS uses Virtual DOM. Virtual DOM compares the previous states of components of an application with the current states and only updates the changes in Real DOM. Whereas, conventional web applications update all components again. This helps ReactJS in creating web applications faster. Extremely Flexible − React allows developers and teams to set their own conventions that they deem are best suited and implement it however they see fit, as there are no strict rules for code conventions in React. Creates dynamic applications easily − Dynamic web applications require less coding while offering more functionality. Thus, ReactJS can create them easily. Develops Mobile Applications as well − Not only web applications, React can also develop mobile applications using React Native. React Native is an open-source UI software framework that is derived from React itself. It uses React Framework to develop applications for Android, macOS, Web, Windows etc. Debugging is Easy − The data flow in React is unidirectional, i.e., while designing an app using React, child components are nested within parent components. As the data flows is in a single direction, it gets easier to debug errors and spot the bugs. Applications Few popular websites powered by React library are listed below − Facebook, popular social media application − React was originally developed at Facebook (or Meta), so its only natural that they use it to run their application. As for their mobile application, it uses React Native to display Android and iOS components, instead of DOM. Facebook”s codebase now includes over 20,000 components and uses the React version that is public. Instagram, popular photo sharing application − Instagram is also completely based on React, as it is powered by Meta as well. The main features to show its usage include Geo-locations, Hashtags, Google Maps APIs etc. Netflix, popular media streaming application − Netflix switched to React in 2015. The factors that mainly influenced this decision are the 1) startup speed to reduce the processing time to render the homepage and enabling dynamic elements in the UI, 2) modularity to allow various features that must coexist with the control experience and 3) runtime performance for efficient UI rendering. Code Academy, popular online training application − Code Academy uses React as the “script is battle-tested, easy to think about, makes SEO easy and is compatible with legacy code and flexible enough for the future”. Reddit, popular content sharing application − Reddit is also developed using React from the scratch. As you see, most popular application in every field is being developed by React Library. ReactJS – Installation This chapter explains the installation of React library and its related tools in your machine. Before moving to the installation, let us verify the prerequisite first. React provides CLI tools for the developer to fast forward the creation, development and deployment of the React based web application. React CLI tools depends on the Node.js and must be installed in your system. Hopefully, you have installed Node.js on your machine. We can check it using the below command − node –version You could see the version of Nodejs you might have installed. It is shown as below for me, v14.2.0 If Nodejs is not installed, you can download and install by visiting https://nodejs.org/en/download/. Toolchain To develop lightweight features such as form validation, model dialog, etc., React library can be directly included into the web application through content delivery network (CDN). It is similar to using jQuery library in a web application. For moderate to big application, it is advised to write the application as multiple files and then use bundler such as webpack, parcel, rollup, etc., to compile and bundle the application before deploying the code. React toolchain helps to create, build, run and deploy the React application. React toolchain basically provides a starter project template with all necessary code to bootstrap the application. Some of the popular toolchain to develop React applications are − Create React App − SPA oriented toolchain Next.js − server-side rendering oriented toolchain Gatsby − Static content oriented toolchain Tools required to develop a React application are

ReactJS – Reference API

ReactJS – Reference API ”; Previous Next React JS is a JavaScript library for building user interfaces. React allows developers to create interactive UI components efficiently. So this reference attempts to document every built-in function, hooks, components, and other essential functionalities provided by React JS. In this tutorial we will use the React@18 version. In the React JS, functions are organized into two main sections based on their functionalities and usage. Here are the main functions in React JS Built-in Hooks In this we have included all the built-in hooks which can be used with different React features in your components. S.No Function & Description 1 use() Lets us read the value of a resource. 2 useDebugValue() Add a label to a custom Hook. 3 useDeferredValue() Lets us defer updating a portion of the User Interface. 4 useId() Use for generating unique IDs. 5 useImperativeHandle() Helps us connect with a child component. 6 useInsertionEffect() Allows us for inserting elements into the DOM. 7 useLayoutEffect() Used to perform the layout measurements. 8 useSyncExternalStore() Lets us subscribe to an external store. 9 useTransition() Help us to update the state without blocking the UI. Built-in Component In this we have documented components you can use in your code and other components as well. S.No Function & Description 1 <Suspense> Display a fallback until its children have finished loading. Built-in React APIs There are some built-in APIs React provides which are useful for defining components. S.No Function & Description 1 cache() Cache the result of a data fetch. 2 createContext() It creates a context that components can provide. 3 lazy() Allows us to delay loading a component”s code. 4 startTransition() Update the state without blocking the UI. Directives These are the instructions for bundlers compatible with React Server Components. S.No Function & Description 1 use client Used to mark what code runs on the client. 2 use server It is used to mark server-side functions. Built-in React DOM Hooks There are some built-in React DOM hooks which run in the browser DOM environment. These Hooks are not best fit for non browser environments like Android, iOS, and Windows applications. S.No Function & Description 1 useFormState() Update state as per the result of a form action. 2 useFormStatus() Gives status information of the last form submission. Event Handling Functions In this section we have included some event handling functions that supports all built−in HTML and SVG components. S.No Function & Description 1 event object Acts as a link between our code and the browser events. 2 AnimationEvent handler An event handler type for the CSS animation events. 3 ClipboardEvent handler It is an event handler type for the Clipboard API events. 4 CompositionEvent handler It is an event handler type for the input method editor events. 5 DragEvent handler Event handler type for the HTML Drag and Drop API events. 6 FocusEvent handler An event handler type for the focus events. 7 InputEvent handler An event handler type for the onBeforeInput event. 8 KeyboardEvent handler Handles events for keyboard events. 9 MouseEvent handler An event handler type for mouse events. 10 PointerEvent handler It is an event handler type for pointer events. 11 TouchEvent handler Event handler type for touch events. 12 TransitionEvent handler An event handler type for the CSS transition events. 13 UIEvent handler Event handler type for generic User Interface events. 14 WheelEvent handler An event handler type for the onWheel event. React DOM APIs The react-dom package contains methods that are only supported for the web applications. In this section we have included APIs, Client APIs and server APIs. S.No Function & Description 1 createPortal() Get the current Axes instance. 2 flushSync() Create a new Axes instance. 3 findDOMNode() Close the current figure. 4 createRoot() Clear the current figure. 5 hydrateRoot() Check if a figure with a given figure number exists. 6 renderToReadableStream() Create a new figure. 7 renderToString() Get the current figure. 8 renderToStaticMarkup() Get the labels of all figures. 9 cloneElement() Set the current Axes instance to a given axes. 10 isValidElement() Add contour labels to a contour plot. 11 PureComponent It is an enhanced version of the regular Component. Other Class components These components are the base class for the React components defined as JavaScript classes. Class components are still supported by React so we have included them in the below section. S.No Function & Description 1 componentDidCatch() Used to call when some child component throws an error. 2 componentDidUpdate() Used to call immediately after component has been

ReactJS – Web Components

ReactJS – Web Components ”; Previous Next React and web components can be mixed in a web application. A react component can have one or more web component and a web component can use react component to create its content. Both options are supported by react. Using Web components in a react application Let us create a web component and then try to apply it in a react application. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a simple web component, HelloMessage (public/WebComponents/HelloMessage.js) and add below code. The purpose of the web component () is to welcome a user (by specifying username in the name attribute of the web component). // web component class HelloMessage extends HTMLElement { constructor() { super(); this.name = ”Folks”; } static get observedAttributes() { return [”name”]; } attributeChangedCallback(property, oldValue, newValue) { if (oldValue === newValue) return; this[property] = newValue; } connectedCallback() { this.textContent = `Hello ${this.name}!`; } } customElements.define(”hello-message”, HelloMessage); Here, connectedCallback() is used to create the content of the web component. observedAttributes function access the name attributes. attributeChangedCallback function updates the value of the name attributes, if it gets changed in the application. customElements.define is used to attach the created web component with a tag name into the web document. Next, open the index.html (public/index.html) file and add the web component as shown below − <!DOCTYPE html> <html lang=”en”> <head> <link rel=”icon” href=”%PUBLIC_URL%/favicon.ico” /> <link rel=”apple-touch-icon” href=”%PUBLIC_URL%/logo192.png” /> <link rel=”manifest” href=”%PUBLIC_URL%/manifest.json” /> <script src=”%PUBLIC_URL%/WebComponents/HelloMessage.js”></script> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div style=”padding: 10px;”> <div id=”root”></div> <div style=”padding: 10px;”> <hello-message name=”John”></hello-message> </div> </div> </body> </html> Here we have, Included the web component in the head section Used the hello-message web component in the page to showcase it”s usage Next, create a simple component, SimpleWebComponent (src/Components/SimpleWebComponent.js) and render the newly created web component as shown below − import React from “react”; class SimpleWebComponent extends React.Component { constructor(props) { super(props) } render() { return ( <hello-message name=”Peter”></hello-message> ); } } export default SimpleWebComponent; Here, the web component hello is used inside the component”s render method. Next, open App component (src/App.js), and use SimpleWebComponent component as shown below − import ”./App.css” import React from ”react”; import SimpleWebComponent from ”./Components/SimpleWebComponent” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleWebComponent /> </div> </div> </div> ); } export default App; Here we have, Imported SimpleWebComponent component from the react package Used SimpleWebComponent component and rendered hello web component Finally, open the application in the browser and check the final result. Summary React and web component complement each other in a nice way. Each has its own advantages and disadvantages and can be used in a single application by analyzing its pros and cons with respect to the application. Print Page Previous Next Advertisements ”;

ReactJS – Static Type Checking

ReactJS – Static Type Checking ”; Previous Next Since JavaScript is a dynamically typed language, it is hard to find type mismatch error before running the code. React support type checking for props through prop-types package, which can be used to identity type mismatch for properties during development phase. The other aspect of the program still needs a tool to properly identify the type issues during development phase. JavaScript has lot of static type checker tools to handle the type problem. We will check two of the popular option, which will integrate smoothly into the workflow of the React application and give hints of the possible type error during development phase of the application. They are as follows − Flow TypeScript language Flow Flow is static type checker for JavaScript. Flow extends the JavaScript language to specify type and allows static type annotation to be set inside the JavaScript code. Flow will check the static type annotation set by the developer in the code and make sure the proper type is used. Otherwise, it will throw error. A simple example is as follows − // @flow function sum(a: number, b: number) : number { return a + b; } sum(10, 20) // Pass sum(“10”, “20”) // Fail Here, // @flow annotation enables the flow static checker to analyze the function defined below. As you see, the function sum uses the Flow language extension to specify the type of the argument. Let us see how to enable Flow in a react project and the development workflow of the Flow enabled react project. Step1 − Create a new react project using create-react-app CLI app. create-react-app myapp Step 2 − Add Flow to the project using below command cd myapp npm install –save-bin flow-bin Step 3 − Now, add Flow command in the scripts of the package.json file { // … “scripts”: { “flow”: “flow”, // … }, // … } This will allow us to run flow command through npm Step 4 − Initialize the flow configuration using flow command as shown below − npm run flow init This will create a basic flow configuration file .flowconfig at the root of the project with below content. [ignore] [include] [libs] [lints] [options] [strict] Advanced flow options can be added here. By default, flow will check all files in our application. To ignore node_modules, add .*/node_modules/.* under [ignore] option. This will instruct the flow application to ignore all files inside the node_modules folder. [ignore] .*/node_modules/.* [include] [libs] [lints] [options] react.runtime=automatic [strict] Step 5 − Now, we have configured the flow into our application. We can use flow annotation into our code and test it against flow using below command npm run flow Flow will check our code and show the similar result in the console as shown below − > [email protected] flow /path/to/myapp > flow Launching Flow server for /path/to/myapp Spawned flow server (pid=1629) Logs will go to /private/tmp/flow/zSUserszSbalazSProjectszSArticleszSreact-revision-v2zSworkspacezSmyapp.log Monitor logs will go to /private/tmp/flow/zSUserszSbalazSProjectszSArticleszSreact-revision-v2zSworkspacezSmyapp.monitor_log No errors! Step 6 − Now, it is fine to use flow annotation in our code. Let us add a simple flow annotation into our code and run the flow command to check the correctness of the code. Create a simple HelloWorld component (src/components/HelloWorld.js) as shown below − import React from ”react” class HelloWorld extends React.Component { render() { return <h1>Hello, {this.props.name}</h1> } } export default HelloWorld Step 7 − Include the component in our root component (App.js) as shown below − // @flow import React from “react”; import HelloWorld from “./components/HelloWorld”; function App() : any { var name: string = 10 return ( <div> <HelloWorld name={name} /> </div> ) } export default App; Step 8 − Now, check the code with flow as shown below npm run flow Flow command will check the code and show the error that the name is set with string value as shown below. > [email protected] flow /path/to/myapp > flow Error ……………………………………..src/App.js:6:22 Cannot assign 10 to name because number [1] is incompatible with string [2]. [incompatible-type] 3│ import HelloWorld from “./components/HelloWorld”; 4│ 5│ function App() : any { [2][1]6│ var name: string = 10 7│ 8│ return ( 9│ <div> Found 1 error ….. ….. Step 9 − Let us fix the error by providing a string value for name variable and rerun the flow command. // @flow import React from “react”; import HelloWorld from “./components/HelloWorld”; function App() : any { var name: string = “John” return ( <div> <HelloWorld name={name} /> </div> ) } export default App; Now, flow command will succeed and show that there is no issue in the code. > [email protected] flow /path/to/myapp > flow No errors! Step 10 − Finally, we can run the app by running below command, npm start The optimized production build can be created using below command, npm run build TypeScript TypeScript is a language with first class support for static typing. Static typing enables TypeScript to catch the type error during compile time instead of runtime. TypeScript support all language features of JavaScript. So, it is really easy for a JavaScript developer to work in TypeScript. React has build-in support for TypeScript. To create a React project, just include TypeScript template during the react app creation through create-react-app. create-react-app myapp –template typescript Once the application is created, add a new HelloWorld component (HelloWorld.tsx) under src/components folder as shown below − // src/components/HelloWorld.tsx import React from ”react” class HelloWorld extends React.Component { render() { return <h1>Hello, {this.props.name}</h1> } } export default HelloWorld Now, include the HelloWorld compon − import React from “react”; import HelloWorld from “./components/HelloWorld”; function App()

ReactJS – Optimizing Performance

ReactJS – Optimizing Performance ”; Previous Next React internally handles the performance of the application and optimize it on every opportunities. As a developer, we can do certain things to get maximum performance of our application. Let us see some of the techniques to get maximum performance out of react library in this chapter. Techniques of Performance Optimization Some of the techniques of performance optimization are as follows − Use production build − React has two mode, development and production. Development mode is for the developers, Development mode enables lot of useful stuff for developer to get better inside of the application and to debug the application. This will slow down the application. To get maximum performance, enable the production mode and deploy the application. CDN Application using cdn to link the react library should use production build of the react library as shown below − <script src=”https://unpkg.com/react@18/umd/react.production.min.js”></script> <script src=”https://unpkg.com/react-dom@18/umd/react-dom.production.min.js”></script> Create react app − Application created using create-react-app CLI can use below command to create production version of the application. npm run build Brunch − Application using brunch should install terser-brunch plugin and then invoke production build to get efficient and performance code. npm install –save-dev terser-brunch brunch build -p Rollup − Application using rollup should install commonjs, replace and terser plugins and configure it to get best production version. npm install –save-dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser Use React devtools − React provides development tools for all browsers as extension. Once the extension is installed, the developer tools section of the browser will show a dedicated section for react. One of the tool provided by react extension is Profiler (React DevTool Profiler). The application can be profiled and optimized before deploying the application to the production. Windowing technique − If the data to be shown in the front end is huge, then the performance of the application will get affected instantly. One way is to show only a small subset of the data through pagination and other similar technique. If those techniques are not feasible, React recommends windowing technique, which will render only a small subset of data at a time automatically. We will learn by applying window technique later in this chapter. Avoid Reconciliation (shouldComponentUpdate) − Reconciliation is a a powerful technique to increase the performance of the react application. Still, reconciliation takes some time to run and apply it in our application. Skipping rendering (and subsequently reconciliation) will improve the performance. React provides an API, shouldComponentUpdate to give hint to the react core whether to skip or continue the rendering. Below code will skip the rendering of the application shouldComponentUpdate(nextProps, nextState) { return false; } Components can analyze its current state and props with its updated one and decide whether the rendering part can be skipped. Pure component − Instead of writing shouldComponentUpdate, write a pure version of component by extending React.PureComponent. Pure component will usually emit same output if the given input is same. Pure component will do the shallow comparison and skip the reconciliation. But, there is one issue. If the changes are no shallow, then react skip the updates and rendering. To fix it, it is enough that the changes are done through visible mutation as shown below − // non-mutation (wrong way to code) const words = this.state.words; words.push(”john”); this.setState({words: words}); // mutated version (right way to code) this.setState(state => ({ words: state.words.concat([”marklar”]) })); Here, In the first version of the code, the object is not mutated. So the comparison with old object succeeds and skip the reconciliation. In the second version of the code, the object is mutated and will get caught during comparison. Applying windowing technique Let us create a new react application to render a large user list by applying windowing technique in this section. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, install the bootstrap and react-bootstrap library using below command, npm install –save react-window Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a file, users.json under public folder and populate with below user information, [ { “id”:1, “name”:”Fowler”, “age”:18 }, { “id”:2, “name”:”Donnell”, “age”:24 }, { “id”:3, “name”:”Pall”, “age”:26 }, { “id”:4, “name”:”Christos”, “age”:19 }, { “id”:5, “name”:”Dud”, “age”:29 }, { “id”:6, “name”:”Rayner”, “age”:22 }, { “id”:7, “name”:”Somerset”, “age”:31 }, { “id”:8, “name”:”Stavros”, “age”:32 }, { “id”:9, “name”:”Cody”, “age”:19 }, { “id”:10, “name”:”Sharai”, “age”:19 }, { “id”:11, “name”:”Kristo”, “age”:28 }, { “id”:12, “name”:”Harvey”, “age”:27 }, { “id”:13, “name”:”Christen”, “age”:27 }, { “id”:14, “name”:”Hillard”, “age”:19 }, { “id”:15, “name”:”Jaine”, “age”:32 }, { “id”:16, “name”:”Annabel”, “age”:29 }, { “id”:17, “name”:”Hildagarde”, “age”:29 }, { “id”:18, “name”:”Cherlyn”, “age”:18 }, { “id”:19, “name”:”Herold”, “age”:32 }, { “id”:20, “name”:”Gabriella”, “age”:32 }, { “id”:21, “name”:”Jessalyn”, “age”:32 }, { “id”:22, “name”:”Opal”, “age”:31 }, { “id”:23, “name”:”Westbrooke”, “age”:27 }, { “id”:24, “name”:”Morey”, “age”:22 }, { “id”:25, “name”:”Carleton”, “age”:26 }, { “id”:26, “name”:”Cosimo”, “age”:22 }, { “id”:27, “name”:”Petronia”, “age”:23 }, { “id”:28, “name”:”Justino”, “age”:32 }, { “id”:29, “name”:”Verla”, “age”:20 }, { “id”:30, “name”:”Lanita”, “age”:18 }, { “id”:31, “name”:”Karlik”, “age”:23 }, { “id”:32, “name”:”Emmett”, “age”:22 }, { “id”:33, “name”:”Abran”, “age”:26 }, { “id”:34, “name”:”Holly”, “age”:23 }, { “id”:35, “name”:”Beverie”, “age”:23 }, { “id”:36, “name”:”Ingelbert”, “age”:27 }, { “id”:37, “name”:”Kailey”, “age”:30 }, { “id”:38, “name”:”Ralina”, “age”:26 }, { “id”:39, “name”:”Stella”, “age”:29 }, { “id”:40, “name”:”Ronnica”, “age”:20 }, { “id”:41, “name”:”Brucie”, “age”:20 }, { “id”:42, “name”:”Ryan”, “age”:22 }, { “id”:43, “name”:”Fredek”, “age”:20 }, { “id”:44, “name”:”Corliss”, “age”:28 }, { “id”:45, “name”:”Kary”, “age”:32 }, { “id”:46, “name”:”Kaylee”, “age”:21 }, { “id”:47, “name”:”Haskell”, “age”:25 }, { “id”:48, “name”:”Jere”, “age”:29 }, { “id”:49, “name”:”Kathryne”, “age”:31 }, { “id”:50, “name”:”Linnea”, “age”:21 }, { “id”:51, “name”:”Theresina”, “age”:24 }, { “id”:52, “name”:”Arabela”, “age”:32 }, { “id”:53, “name”:”Howie”,

ReactJS – Animation

ReactJS – Animation ”; Previous Next Animation is an exciting feature of modern web application. It gives a refreshing feel to the application. React community provides many excellent react based animation library like React Motion, React Reveal, react-animations, etc., React itself provides an animation library, React Transition Group as an add-on option earlier. It is an independent library enhancing the earlier version of the library. Let us learn React Transition Group animation library in this chapter. React Transition Group React Transition Group library is a simple implementation of animation. It does not do any animation out of the box. Instead, it exposes the core animation related information. Every animation is basically transition of an element from one state to another. The library exposes minimum possible state of every element and they are given below − Entering Entered Exiting Exited The library provides options to set CSS style for each state and animate the element based on the style when the element moves from one state to another. The library provides in props to set the current state of the element. If in props value is true, then it means the element is moving from entering state to exiting state. If in props value is false, then it means the element is moving from exiting to exited. Installation To install this React Transition Group library, use either of the following commands − # npm npm install react-transition-group –save # yarn yarn add react-transition-group Transition Transition is the basic component provided by the React Transition Group to animate an element. Let us create a simple application and try to fade in / fade out an element using Transition element. First, create a new react application, react-animation-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, install React Transition Group library. cd /go/to/project npm install react-transition-group –save Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create components folder under src folder. Next, create a file, HelloWorld.js under src/components folder and start editing. Next, import React and animation library. import React from ”react”; import { Transition } from ”react-transition-group” Next, create the HelloWorld component. class HelloWorld extends React.Component { constructor(props) { super(props); } } Next, define transition related styles as JavaScript objects in the constructor. this.duration = 2000; this.defaultStyle = { transition: `opacity ${this.duration}ms ease-in-out`, opacity: 0, } this.transitionStyles = { entering: { opacity: 1 }, entered: { opacity: 1 }, exiting: { opacity: 0 }, exited: { opacity: 0 }, }; Here, defaultStyles sets the transition animation transitionStyles set the styles for various states Next, set the initial state for the element in the constructor. this.state = { inProp: true } Next, simulate the animation by changing the inProp values every 3 seconds. setInterval(() => { this.setState((state, props) => { let newState = { inProp: !state.inProp }; return newState; }) }, 3000); Next, create a render function. render() { return ( ); } Next, add Transition component. Use this.state.inProp for in prop and this.duration for timeout prop. Transition component expects a function, which returns the user interface. It is basically a Render props. render() { return ( <Transition in={this.state.inProp} timeout={this.duration}> {state => ({ … component”s user interface. }) </Transition> ); } Next, write the components user interface inside a container and set the defaultStyle and transitionStyles for the container. render() { return ( <Transition in={this.state.inProp} timeout={this.duration}> {state => ( <div style={{ …this.defaultStyle, …this.transitionStyles[state] }}> <h1>Hello World!</h1> </div> )} </Transition> ); } Finally, expose the component. export default HelloWorld The complete source code of the component is as follows − import React from “react”; import { Transition } from ”react-transition-group”; class HelloWorld extends React.Component { constructor(props) { super(props); this.duration = 2000; this.defaultStyle = { transition: `opacity ${this.duration}ms ease-in-out`, opacity: 0, } this.transitionStyles = { entering: { opacity: 1 }, entered: { opacity: 1 }, exiting: { opacity: 0 }, exited: { opacity: 0 }, }; this.state = { inProp: true } setInterval(() => { this.setState((state, props) => { let newState = { inProp: !state.inProp }; return newState; }) }, 3000); } render() { return ( <Transition in={this.state.inProp} timeout={this.duration}> {state => ( <div style={{ …this.defaultStyle, …this.transitionStyles[state] }}> <h1>Hello World!</h1> </div> )} </Transition> ); } } export default HelloWorld; Next, create a file, index.js under the src folder and use HelloWorld component. import React from ”react”; import ReactDOM from ”react-dom”; import HelloWorld from ”./components/HelloWorld”; ReactDOM.render( <React.StrictMode <HelloWorld / </React.StrictMode , document.getElementById(”root”) ); Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”utf-8″> <title>React Containment App</title> </head> <body> <div id=”root”></div> <script type=”text/JavaScript” src=”./index.js”></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Clicking the remove link will remove the item from redux store. To learn more about animating elements using React Transition Group, click here. CSSTransition CSSTransition is built on top of Transition component and it improves Transition component by introducing classNames prop. classNames prop refers the css class name used for various state of the element. For example, classNames=hello prop refers below css classes. .hello-enter { opacity: 0; } .hello-enter-active { opacity: 1; transition: opacity 200ms; } .hello-exit { opacity: 1; } .hello-exit-active { opacity: 0; transition: opacity 200ms; } Let us create a new component HelloWorldCSSTransition using CSSTransition component. First, open our