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
Category: reactjs
ReactJS – Using useCallback
ReactJS – useCallback ”; Previous Next The useCallback hook is similar to useMemo hook and provides the functionality of memoizing the function instead of values. Since callback function in an integral part of the JavaScript programming and callback functions are passed by references, react provides a separate hook, useCallback to memoize the callback functions. In theory, useCallback functionality can be done using useMemo hook itself. But, useCallback improves the readability of the react code. Signature of the useCallback hook The signature of the useCallback hook is as follows − const <memoized_callback_fn> = useCallback(<callback_fn>, <dependency_array>); Here, the useCallback accepts two input and returns a memoized callback function. The input parameter are as follows − callback_fn − Callback function to be memorized. dependency_array − Hold variables, upon which the callback function depends. The output of the useCallback hook is the memoized callback function of the callback_fn. Usage of useCallback hook is as follows − const memoizedCallbackFn = useCallback(() => { // code }, [a, b]) Note − The useCallback(callback_fn, dependency_array) is equivalent to useMemo(() => callback_fn, dependency_array). Applying useCallback Let us learn how to apply the useCallback hook by creating a react application. First of all, create and start a react application by using create-react-app command as shown below − create-react-app myapp cd myapp npm start Next, create a component, PureListComponent under components folder (src/components/PureListComponent.js) import React from “react”; function PureListComponent() { return <div>List</div> } export default PureListComponent Next, update the root component with PureListComponent component as shown below − import PureListComponent from ”./components/PureListComponent”; function App() { return ( <div style={{ padding: “5px” }}> <PureListComponent /> </div> ); } export default App; Next, open PureListComponent.js and add two props list of items to show in the component callback function to show the item clicked by user in the console import React from “react”; function PureListComponent(props) { const items = props[”items”]; const handleClick = props[”handleClick”] console.log(“I am inside the PureListComponent”) return ( <div> {items.map((item, idx) => <span key={idx} onClick={handleClick}>{item} </span> )} </div> ) } export default React.memo(PureListComponent) Here we have, Used items props to get the list of items Used handleClick to get the handler for click event Wrapped the component using React.memo to memoize the component. Since the component will render same output for the given set of input, it is called PureComponent in react. Next, let us update App.js and use the PureListComponent as shown below − import React, {useState, useEffect} from ”react”; import PureListComponent from ”./components/PureListComponent”; function App() { // array of numbers var listOfNumbers = […Array(100).keys()]; // callback function const handleCallbackFn = (e) => { console.log(e.target.innerText) } const [currentTime, setCurrentTime] = useState(new Date()) useEffect(() => { let interval = setInterval(() => { setCurrentTime(new Date()) }, 1000) return () => clearInterval(interval) }, [currentTime]) return ( <div style={ { padding: “5px” } }> <PureListComponent items={listOfNumbers} handleClick={handleCallbackFn}/> <div>Time: <b>{currentTime.toLocaleString().split(”,”)[1]}</b></div> </div> ); } export default App; Here we have Included a state, currentTime and updated it every second using setInterval to make sure the component rerenders every second. We may thought that PureListComponent will not rerender every second as it uses React.memo. But, it will rerender as the props value are of reference type. Next, update the root component and use useMemo and useCallback to preserve the array and callback function as shown below − import React, {useState, useEffect, useCallback, useMemo} from ”react”; import PureListComponent from ”./components/PureListComponent”; function App() { // array of numbers const listOfNumbers = useMemo(() => […Array(100).keys()], []); // callback function const handleCallbackFn = useCallback((e) => console.log(e.target.innerText), []) const [currentTime, setCurrentTime] = useState(new Date()) useEffect(() => { let interval = setInterval(() => { setCurrentTime(new Date()) }, 1000) return () => clearInterval(interval) }, [currentTime]) return ( <div style={ { padding: “5px” } }> <PureListComponent items={listOfNumbers} handleClick={handleCallbackFn}/> <div>Time: <b>{currentTime.toLocaleString().split(”,”)[1]}</b></div> </div> ); } export default App; Here we have, Used useMemo to preserve the items array Used useCallback to preserve the handleClick callback functions Finally, check the application in the browser and it will not rerender PureListComponent every second. Use cases of useCallback Some of the use cases of the useCallback hook is as follows − Pure functional component with function props useEffect or other hooks having function as dependency Usage of function during debouncing / throttling or similar action Advantages Advantages of useCallback hook are as follows − Simple to use API Easy to understand Improves the performance of the application Disadvantages Technically, useCallback have no disadvantages. But, heavy usage of useCallback in a application will bring below disadvantages. Decrease the readability of the application Decrease the Understandability of the application Debugging the application is complex Developer should have deep understanding of JavaScript language to use it Summary useCallback is easy to use and improves performance. At the same time, useCallback should be used only when it is absolutely necessary. It should not be used in every scenario. The general rule is check the performance of the application. if it needs improvement, then we can check whether the usage of useCallback will help to improve the performance. If we get positive response, then we can use it. Otherwise, we can leave it to the react to improve and optimize the performance of the application. Print Page Previous Next Advertisements ”;
ReactJS – Discussion
Discuss ReactJS ”; Previous Next React is an open source, JavaScript library for developing user interface (UI) in web application. React is developed and released by Facebook. Facebook is continuously working on the React library and enhancing it by fixing bugs and introducing new features. This tutorial starts with the architecture of React, how-to guide to setup projects, creating components, JSX and then walks through advanced concepts like state management, form programming, routing and finally conclude with step by step working example. Print Page Previous Next Advertisements ”;
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 ”; 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 ”; 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
ReactJS – Bootstrap
ReactJS – Bootstrap ”; Previous Next Bootstrap is a popular CSS framework used by the front-end developer around the world. Bootstrap provides an excellent support for designing web pages through its flexible, responsive and high performance utility CSS components. Bootstrap also provides a large collection of jQuery based UI components. Using bootstrap CSS and JavaScript components, front-end developer can design beautiful webpages along with responsive support for any devices. React can be used along with Bootstrap and get all benefits of Bootstrap in their web application. Let us see how to integrate Bootstrap into React application in this chapter. Integrating Bootstrap Bootstrap can be integrated into React application through multiple ways. If a developer wants to use only CSS features from the bootstrap library, then the developer can import the bootstrap library through CDN and use the bootstrap CSS class in the required places. If a developer wants to use Bootstrap JavaScript library, then the developer can either use react components wrapped around the original bootstrap jQuery component or special react UI library designed to exploit the features of bootstrap library. Below is the list of options to integrate bootstrap library into React application. Link tag (CSS only). import feature (CSS only). Link tag (Bootstrap + jQuery UI). Wrapper react component. Native react bootstrap component. Link tag (CSS only) Let us learn how to apply link tag by creating a react application in this chapter. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, open main html page (public/index.html) and include below tag in the head <!– CSS only –> <link href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css” rel=”stylesheet” integrity=”sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi” crossorigin=”anonymous”> Next, open App.css (src/App.css) and update the CSS to set the margin for button elements. button { margin: 5px; } Next, open App component (src/App.js) and update the content with bootstrap button as shown below − import ”./App.css” function App() { return ( <div className=”container”> <button type=”button” class=”btn btn-primary”>Primary</button> <button type=”button” class=”btn btn-secondary”>Secondary</button> <button type=”button” class=”btn btn-success”>Success</button> <button type=”button” class=”btn btn-danger”>Danger</button> <button type=”button” class=”btn btn-warning”>Warning</button> <button type=”button” class=”btn btn-info”>Info</button> <button type=”button” class=”btn btn-light”>Light</button> <button type=”button” class=”btn btn-dark”>Dark</button> <button type=”button” class=”btn btn-link”>Link</button> </div> ); } export default App; Here, Applied bootstrap CSS class for different type of buttons. Included the App.css style. Finally, open the application in the browser and check whether the bootstrap classes are properly applied in the button elements as shown below − import feature (CSS only) Let us see how to integrate the bootstrap CSS using import feature 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 library using below command. npm install –save bootstrap Next, open App.css (src/App.css) and update the CSS to set the margin for button elements. button { margin: 5px; } Next, open App component (src/App.js), import the bootstrap css and update the content with bootstrap button as shown below − // Bootstrap CSS import “bootstrap/dist/css/bootstrap.min.css”; // Bootstrap Bundle JS import “bootstrap/dist/js/bootstrap.bundle.min”; import ”./App.css” function App() { return ( <div className=”container”> <button type=”button” class=”btn btn-primary”>Primary</button> <button type=”button” class=”btn btn-secondary”>Secondary</button> <button type=”button” class=”btn btn-success”>Success</button> <button type=”button” class=”btn btn-danger”>Danger</button> <button type=”button” class=”btn btn-warning”>Warning</button> <button type=”button” class=”btn btn-info”>Info</button> <button type=”button” class=”btn btn-light”>Light</button> <button type=”button” class=”btn btn-dark”>Dark</button> <button type=”button” class=”btn btn-link”>Link</button> </div> ); } export default App; Here we have − Imported the bootstrap classes using import statement. Applied bootstrap CSS class for different type of buttons. Included the App.css style. Finally, open the application in the browser and check whether the bootstrap classes are properly applied in the button elements as shown below − Link tag (Bootstrap + jQuery UI) React allows the developer to integrate the react component into specific part of the webpage using createRoot method. This feature enables developer to use React and Bootstrap component in a single webpage. Developer can mix both libraries without affecting each other. This is the simple and best option for small webpage. Since it does not need any extra learning, it is easy and safe to implement in a web application. Wrapper react component Developer can create a wrapper react component for the necessary bootstrap component and can use it in their application. This method can be used for moderate to complex web application where bootstrap component is not extensively used. Native react bootstrap component React community created many component library integrating Bootstrap and React. Some of the popular libraries are as follows − React-Bootstrap (https://react-bootstrap.github.io/) Bootstrap 4 React (https://bootstrap-4-react.com//) Reactstrap (https://reactstrap.github.io/) Bootstrap React from coreUI (https://coreui.io/bootstrap-react/) Let us see how to use React-bootstrap in this chapter by creating a simple 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, install the bootstrap library using below command, npm install –save react-bootstrap bootstrap Next, open App.css (src/App.css) and update the CSS to set the margin for button elements. button { margin: 5px; } Next, open App component (src/App.js), import the bootstrap css and update the content with bootstrap button as shown below − // Bootstrap CSS import “bootstrap/dist/css/bootstrap.min.css”; // Bootstrap Bundle JS import “bootstrap/dist/js/bootstrap.bundle.min”; import ”./App.css” import { Button } from ”react-bootstrap”; function App() { return ( <div className=”container”> <Button variant=”primary”>Primary</Button>{” ”} <Button variant=”secondary”>Secondary</Button>{” ”} <Button variant=”success”>Success</Button>{” ”} <Button variant=”warning”>Warning</Button>{” ”} <Button variant=”danger”>Danger</Button>{” ”} <Button variant=”info”>Info</Button>{” ”} <Button variant=”light”>Light</Button>{” ”} <Button variant=”dark”>Dark</Button> <Button variant=”link”>Link</Button> </div> ); } export default App; Here we have − Imported the bootstrap classes using import
ReactJS – Map
ReactJS – Map ”; Previous Next JavaScript Array datatype provides a range of easy to use function to manipulate the array and its values. The map() is one such function, which accepts a transform function and will create a new array by transforming each item in the given array by applying the transform function and return the newly created array. The signature of the map function is as follows − array.map(function(item, index, items), thisValue) Here, currentValue refers the value of the current element index refers the index value of the current element items refers the array of the current element thisValue is the optional this value, which can be passed while invoking the map function Let us consider that we have a list of numbers and wants to double each value in the array. We can do it in one line using map function as shown below − var numbers = [2, 4, 6] var transformed = numbers.map((val) => val + val) for(var item of transformed) { console.log(item) } Here, the output wil be as follows − 4 8 12 Example Let us create a new application using create-react-app and start the application. create-react-app myapp cd myapp npm start Next, create a component, ExpenseListUsingForLoop under components folder (src/components/ExpenseListUsingForLoop.js). import React from ”react” class ExpenseListUsingForLoop extends React.Component { render() { return <table> <thead> <tr> <th>Item</th> <th>Amount</th> </tr> </thead> <tbody> </tbody> <tfoot> <tr> <th>Sum</th> <th></th> </tr> </tfoot> </table> } } export default ExpenseListUsingForLoop Here, we created a basic table structure with header and footer. Next, create a function to find the total expense amount. We will use it later in the render method. getTotalExpenses() { var items = this.props[”expenses”]; var total = 0; for(let i = 0; i < items.length; i++) { total += parseInt(items[i]); } return total; } Here, getTotalExpenses loop over the expense props and summarize the total expenses. Next, add expense items and total amount in the render method. render() { var items = this.props[”expenses”]; var expenses = [] expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>) var total = this.getTotalExpenses(); return <table> <thead> <tr> <th>Item</th> <th>Amount</th> </tr> </thead> <tbody> {expenses} </tbody> <tfoot> <tr> <th>Sum</th> <th>{total}</th> </tr> </tfoot> </table> } Here we have, Navigated each item in the expense array using map function, created table row (tr) for each entry using transform function and finally set the returned array in expenses variable. Used expenses array in the JSX expression to include the generated rows. Used getTotalExpenses method to find the total expense amount and add it into the render method. The complete source code of the ExpenseListUsingForLoop component is as follows − import React from ”react” class ExpenseListUsingForLoop extends React.Component { getTotalExpenses() { var items = this.props[”expenses”]; var total = 0; for(let i = 0; i < items.length; i++) { total += parseInt(items[i]); } return total; } render() { var items = this.props[”expenses”]; var expenses = [] expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>) var total = this.getTotalExpenses(); return <table> <thead> <tr> <th>Item</th> <th>Amount</th> </tr> </thead> <tbody> {expenses} </tbody> <tfoot> <tr> <th>Sum</th> <th>{total}</th> </tr> </tfoot> </table> } } export default ExpenseListUsingForLoop Next, update the App component (App.js) with ExpenseListUsingForLoop component. import ExpenseListUsingForLoop from ”./components/ExpenseListUsingForLoop”; import ”./App.css”; function App() { var expenses = [100, 200, 300] return ( <div> <ExpenseListUsingForLoop expenses={expenses} /> </div> ); } export default App; Next, add include a basic styles in App.css /* Center tables for demo */ table { margin: 0 auto; } div { padding: 5px; } /* Default Table Style */ table { color: #333; background: white; border: 1px solid grey; font-size: 12pt; border-collapse: collapse; } table thead th, table tfoot th { color: #777; background: rgba(0,0,0,.1); text-align: left; } table caption { padding:.5em; } table th, table td { padding: .5em; border: 1px solid lightgrey; } Finally, check the application in the browser. It will show the expenses as shown below − Map in JSX JSX allows any JavaScript expression to be included in it. Since map is just an expression in JavaScript, we can use it directly inside the JSX as shown below − render() { var items = this.props[”expenses”]; var expenses = [] // expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>) var total = this.getTotalExpenses(); return <table> <thead> <tr> <th>Item</th> <th>Amount</th> </tr> </thead> <tbody> {items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>)} </tbody> <tfoot> <tr> <th>Sum</th> <th>{total}</th> </tr> </tfoot> </table> } export default ExpenseListUsingForLoop Print Page Previous Next Advertisements ”;