ReactJS – BrowserRouter

ReactJS – BrowserRouter ”; Previous Next Routing is one of the important concept in a front end application. React community provides an excellent router library called React Router. Let us learn the concept of React router and how to use it in a react application in this chapter. Router concepts The primary purpose of the router is to match the given url to a react component and render the matched component. In addition to matching and rendering, the router should manage the history of the browser as well for an efficient forward and backward navigation in the browser. Before understanding the how the router works, let us know some of the useful components of react router library. BrowserRouter − BrowserRouter is top level component. It creates a history (navigation history), put the initial location (router object representing “where the user is at”) into the react state and finally subscribes to the location URL. <BrowserRouter> <!– children –> </BrowserRouter> Routes − Routes will recurses it”s child node and build a router configuration. It matches the configured routes against the location and render the first matched route element. <BrowserRouter> <Routes> <Route path=”/” element={<App />}> <Route index element={<Home />} /> <Route path=”admin” element={<Admin />}> <Route path=”product” element={<ProductListing />} /> <Route path=”category” element={<CategoryListing />} /> <Route index element={<Dashboard />} /> </Route> </Route> <Route path=”/login” element={<Login />}> <!– more nested routes –> </Route> <!– more routes –> </Routes> </BrowserRouter> Here, / path is mapped to App component. / path”s index component is mapped to Home component. /admin path is mapped to Admin component. /admin path”s index component is mapped to Dashboard component. /admin/product path is matched to ProductListing component. /admin/category path is matched to CategoryListing component. /admin/dashboard path is matched to Dashboard component. Route − Route is the actual router configuration. It can be nested to any level similar to folders. Outlet − Outlet component renders the next match in a set of matches. function Hello() { return ( <div>Hello</div> <Outlet /> ) } Here, Placed the Outlet component at the bottom of the hello component. Router will render the next match inside the Outlet component. Link − Link component is similar to anchor tag and used for navigation purpose. Once the user click on it, it changes the location based on it”s to props <Link to=”/admin” /> navigate() − navigate() is an API used for navigation purpose similar to Link component. navigate(“/admin”) Router workflow Let us consider a react application has two five pages / components as shown below − Home (/) Contact (/contact) Register (/register) Admin (/admin) AdminDashboard (/admin/dashboard) A sample router configuration is as follows − <BrowserRouter> <Routes> <Route path=”/” element={<App />}> <Route index element={<Home />} /> <Route path=”contact” element={<Contact />} /> <Route path=”register” element={<Register />} /> <Route path=”admin” element={<Admin />}> <Route path=”dashboard” element={<AdminDashboard />} /> <Route path=”category” element={<CategoryListing />} /> <Route index element={<AdminDashboard />} /> </Route> </Routes> </BrowserRouter> Let us see how admin dashboard url (/admin/dashboard) will get matched and rendered by the react router. At First of all, react library will render our application. Since our application will have BrowserRouter at the top of the render tree, it gets called and rendered BrowserRouter component creates a history, put the initial location in the state and subscribe to the url Routes component will checks all its children, build the router configuration and finally render the first match (/admin => ) Admin component will be rendered. It will have an Outlet component as shown below – function Admin() { return ( <div> <!– Admin content –> </div> <Outlet /> ) } Outlet component renders the next match within itself (/admin/dashboard => ) User may click a link (Link component) in the dashboard, say “/admin/category” Link component calls the navigate(“/admin/category“) method The history (object) changes the url and notifies the BrowserRouter As BrowserRouter component is already subscribed to the url, BrowserRouter component will be rerendered and the whole process will be repeated (from 2) How to apply routers 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 router library using below command, npm install –save react-router-dom Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a folder, Pages under src and create a new home page component, Home (src/Pages/Home.js) and render simple home page content as shown below − function Home() { return <h3>Home</h3> } export default Home Next, create a new greeting page component, Greeting (src/Pages/Greeting.js) and render simple greeting message as shown below − function Greeting() { return <h3>Hello World!</h3> } export default Greeting; Next, open App.js file and render a BrowserRoutes component as shown below − import ”./App.css” import React from ”react”; import { BrowserRouter, Route, Routes } from ”react-router-dom”; import Layout from ”./Pages/Layout”; import Home from ”./Pages/Home”; import Greeting from ”./Pages/Greeting”; function App() { return ( <BrowserRouter> <Routes> <Route path=”/” element={<Layout />}> <Route index element={<Home />} /> <Route path=”greet” element={<Greeting />} /> </Route> </Routes> </BrowserRouter> ); } export default App; Here, BrowserRouter is the main component. It will have router setting as its children and render the entire application based on the router setting. Routes is the main router component. It holds a list of individual router setting. Route is the actual router component having the mapping between web path (/home) and the component (Home). Route can be nested to support nested paths. The mapping defined in the routes

ReactJS – Using useRef

ReactJS – useRef ”; Previous Next React automatically emits the HTML elements as the state of the component changes. This greatly simplifies the UI development as it is enough to update the state of the component. Traditionally, it is normal to access the DOM element directly to update the UI of the component. Sometimes we may need to fallback to accessing the DOM elements directly and update the UI of the component. React ref lends help in this scenario. It provides direct access to DOM elements. Also, it make sure that the component work smoothly with react Virtual DOM and HTML DOM. React provides a function, createRef to create ref in class based component. The counterpart of createRef in function component is useRef hook. Let us learn how to use useRef in this chapter. Signature of the useRef hook The purpose of the useRef is to return a mutable object, which will persist between rerenders. The signature of useRef is as follows − <refObj> = useRef(<val>) Here, val is the initial value to be set for the returned mutable object, refObj. refObj is the object returned by the hook. To automatically attach a DOM object to the refObj, it should be set in ref props of the element as shown below − <input ref={refObj} /> To access the attached DOM element, use current property of the refObj as shown below − const refElement = refObj.current Applying ref hook Let us learn how to apply useRef 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, create a react component, RefInput under component folder (src/components/RefInput.js) function RefInput() { return <div>Hello World</div> } export default RefInput Next, update the root component (App.js) to use our new component. import RefInput from “./components/RefInput”; function App() { return ( <div style={{ padding: “5px”}}> <RefInput /> </div> ); } export default App; Next, add a counter functionality to RefInput component as shown below − import {useState} from ”react” function RefInput() { const [count, setCount] = useState(0) const handleClick = () => setCount(count + 1) return ( <div> <div>Counter: {count} <button onClick={handleClick}>+</button></div> </div> ) } export default RefInput Here we have, Used useState hook to handle counter state variable (count). Rendered the counter state variable in the JSX. Added a button and attached a click handler event (handleClick), which will increment the counter using setCount method. Next, add an input field and show a greeting message based on the value entered by user in the input field as shown below − import {useState, useRef} from ”react” function RefInput() { const [count, setCount] = useState(0) const inputRef = useRef(null) const labelRef = useRef(null) console.log(“RefInput is (re)rendered”) const handleClick = () => setCount(count + 1) const handleChange = () => labelRef.current.innerText = inputRef.current. value == “” ? “World” : inputRef.current.value return ( <div> <div>Counter: {count} <button onClick={handleClick}>+</button></div> <div style={{ paddingTop: “5px”}}> <label>Enter your name: </label><input type=”text” name=”username” ref={inputRef} onChange={handleChange}/> <br /> <div>Hello, <span ref={labelRef}></span></div> </div> </div> ) } export default RefInput Here we have − Created a ref, inputRef to represent the input element and attached it to the relevant element through ref props. Created another ref, labelRef to represent the greeting message element and attached it to the relevant element through ref props. Attached an event handler, handleChange to the input element. The event handler uses inputRef ref to get the greeting message and uses labelRef ref to update the message. Next, open the application in the browser and enter your name. Application will update the greeting message as shown below. Check your console and you can notice that the component is not rerendered. Since react rerenders only on state changes and ref does not do any state changes, the component is not rerendered. Next, click the + button. It will update the counter by rerendering the component as there is change in state (count). If you notice closely, you can find that the message remains same. The reason for this behavior is that the ref values are preserved between rendering by the react. Use cases of useRef Some of the use cases of useRef are as follows − Accessing JavaScript DOM API − JavaScript DOM API provides rich set of feature to manipulate the UI of the application. When the application feature need access to JavaScript DOM API, useRef can be used to retrieve the raw DOM object. Once the raw DOM object is retrieved, the application can use the DOM API to access all the features. Some of the examples of DOM API are as follows − Focusing an input element Selecting text play audio or video using media playback API Imperative animation − Web Animation API provides a rich set of animation feature through imperative programming rather than declarative programming. To use Web animation API, we need access to the raw DOM. Integration with third party library − Since third party library requires access to raw DOM to do its functionality, it is be mandatory to use useRef to get the DOM reference from react and provide it to third party library. Summary Even though react way of developing UI is simple and easy, developing UI based on DOM API has it own advantages in certain scenario. useRef hook fits perfectly in those scenario and provides simple and clean API to access the DOM element directly and subsequently its API. Print Page Previous Next Advertisements ”;

ReactJS – Profiler API

ReactJS – Profiler API ”; Previous Next Profiling is an important technique to collect and show the time taken for a specific function to execute in the live environment. Profiling is normally use to find the performance bottleneck in a application. React provides two option to profile a react application Profiler Component Profiler DevTools Profiler Component React profiler component is just another react component used to record the profile information of a react component. Profiler component can be used anywhere in the react element tree. React accepts multiple profiler and multi-level nesting of the profiler. Let us check the signature and how to apply profiler in a react application in this chapter. Signature of the Profiler component Profiler component can nest any react component and requires two props, id Identifier for the profiler component onRender callback function Callback function called during each phase of the component rendering The signature of the callback function is as follows − function onRenderCallback( id, phase, actualDuration, baseDuration, startTime, commitTime, interactions ){ // Do anything with the profiler information } An example callback function implementation to log the profiling data in the console is as follows − const logProfilerData = (id, phase, actualTime, baseTime, startTime, commitTime) => { console.log(`${id}”s ${phase} phase:`); console.log(`Actual time: ${actualTime}`); console.log(`Base time: ${baseTime}`); console.log(`Start time: ${startTime}`); console.log(`Commit time: ${commitTime}`); }; Applying Profiler Let us create a new react application to learn how to apply Profiler component 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. // remove all css classes Next, create a simple hello component, Hello (src/Components/Hello.js) and render a simple message as shown below − import React from “react”; class Hello extends React.Component { constructor(props) { super(props) } render() { return ( <div>Hello, {this.props.name}</div> ); } } export default Hello; Here, Used name props to render the hello message with the given name Next, open App component (src/App.js), and use profiler component as shown below − import ”./App.css” import React, { Profiler } from ”react”; import Hello from ”./Components/Hello” const logProfilerData = (id, phase, actualTime, baseTime, startTime, commitTime) => { console.log(`${id}”s ${phase} phase:`); console.log(`Actual time: ${actualTime}`); console.log(`Base time: ${baseTime}`); console.log(`Start time: ${startTime}`); console.log(`Commit time: ${commitTime}`); }; function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Profiler id=”helloWorld” onRender={logProfilerData}> <Hello name=”World” /> </Profiler> </div> </div> </div> ); } export default App; Here, Imported Profiler component from the react package Used Hello component by wrapping it with Profiler component Created a callback function, logProfilerData and emitted all profiler data into the console Set the logProfilerData callback function in onRender props of Profiler component Finally, open the application in the browser and check the final result. It will render the hello component as shown below − Open the console and you can see the profiler information as shown below − helloWorld”s mount phase: App.js:7 Actual time: 4.900000000372529 App.js:8 Base time: 1.800000000745058 App.js:9 Start time: 515.7999999988824 App.js:10 Commit time: 525.9000000003725 … App.js:6 helloWorld”s update phase: App.js:7 Actual time: 1 App.js:8 Base time: 0.6999999992549419 App.js:9 Start time: 19836.900000000373 App.js:10 Commit time: 19838.400000000373 Profiler React DevTools React DevTools plugin introduced a separate section for profiler. Developer can open the Profiler tab and get lot of useful insight about the application. Some of the feature available in profiler DevTools are as follows − Browsing commits Filtering commits Flame chart Ranked chart Component chart Conclusion React profiler component and profiler devtools are indispensible and powerful tools to profile and optimize a react application. Print Page Previous Next Advertisements ”;

ReactJS – Layout Component

ReactJS – Layout in Component ”; Previous Next One of the advanced features of React is that it allows arbitrary user interface (UI) content to be passed into the component using properties. As compared to React”s special children property, which allows only a single user interface content to be passed into the component, this option enables multiple UI content to be passed into the component. This option can be seen as an extension of children property. One of the use cases of this option is to layout the user interface of a component. For example, a component with customizable header and footer can use this option to get the custom header and footer through properties and layout the content. Example A quick and simple example with two properties, header and footer is given below <Layout header={<h1>Header</h1>} footer={<p>footer</p>} /> And the layout render logic is as follows − return (<div> <div> {props.header} </div> <div> Component user interface </div> <div> {props.footer} </div> </div>) Let us add a simple header and footer to our expense entry list (ExpenseEntryItemList) component. Open expense-manager application in your favorite editor. Next, open the file, ExpenseEntryItemList.js in src/components folder. Next, use header and footer props in the render() method. return ( <div> <div>{this.props.header}</div> … existing code … <div>{this.props.footer}</div> </div> ); Next, open index.js and include header and footer property while using the ExpenseEntryItemList component. ReactDOM.render( <React.StrictMode> <ExpenseEntryItemList items={items} header={ <div><h1>Expense manager</h1></div> } footer={ <div style={{ textAlign: “left” }}> <p style={{ fontSize: 12 }}>Sample application</p> </div> } /> </React.StrictMode>, document.getElementById(”root”) ); 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. Sharing logic in component aka Render props Render props is an advanced concept used to share logic between React components. As we learned earlier, a component can receive arbitrary UI content or React elements (objects) through properties. Usually, the component render the React elements it receives as is along with its own user interface as we have seen in children and layout concept. They do not share any logic between them. Going one step further, React allows a component to take a function which returns user interface instead of plain user interface object through properties. The sole purpose of the function is to render the UI. Then, the component will do advanced computation and will call the passed in function along with computed value to render the UI. In short, component”s property, which accepts a JavaScript function that renders user interface is called Render Props. Component receiving Render Props will do advanced logic and share it with Render Props, which will render the user interface using the shared logic. Lot of advanced third-party library are based on Render Props. Some of the libraries using Render Props are − React Router Formik Downshift For example, Formik library component will do the form validation and submission and pass the form design to the calling function aka Render Props. Similarly, React Router do the routing logic while delegating the UI design to other components using Render Props. Print Page Previous Next Advertisements ”;

ReactJS – Http client programming

ReactJS – Http Client Programming ”; Previous Next Http client programming enables the application to connect and fetch data from http server through JavaScript. It reduces the data transfer between client and server as it fetches only the required data instead of the whole design and subsequently improves the network speed. It improves the user experience and becomes an indispensable feature of every modern web application. Nowadays, lot of server side application exposes its functionality through REST API (functionality over HTTP protocol) and allows any client application to consume the functionality. React does not provide it”s own http programming api but it supports browser”s built-in fetch() api as well as third party client library like axios to do client side programming. Let us learn how to do http programming in React application in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter. Expense Rest API Server The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. React provides support to create client side application. Express a popular web framework provides support to create server side application. Let us first create a Expense Rest Api server using express framework and then access it from our ExpenseManager application using browser”s built-in fetch api. Open a command prompt and create a new folder, express-rest-api. cd /go/to/workspace mkdir apiserver cd apiserver Initialize a new node application using the below command − npm init The npm init will prompt and ask us to enter basic project details. Let us enter apiserver for project name and server.js for entry point. Leave other configuration with default option. This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (apiserver) version: (1.0.0) description: Rest api for Expense Application entry point: (index.js) server.js test command: git repository: keywords: author: license: (ISC) About to write to pathtoworkspaceexpense-rest-apipackage.json: { “name”: “expense-rest-api”, “version”: “1.0.0”, “description”: “Rest api for Expense Application”, “main”: “server.js”, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “author”: “”, “license”: “ISC” } Is this OK? (yes) yes Next, install express, nedb & cors modules using below command − npm install express nedb cors express is used to create server side application. nedb is a datastore used to store the expense data. cors is a middleware for express framework to configure the client access details. Next, let us create a file, data.csv and populate it with initial expense data for testing purposes. The structure of the file is that it contains one expense entry per line. Pizza,80,2020-10-10,Food Grape Juice,30,2020-10-12,Food Cinema,210,2020-10-16,Entertainment Java Programming book,242,2020-10-15,Academic Mango Juice,35,2020-10-16,Food Dress,2000,2020-10-25,Cloth Tour,2555,2020-10-29,Entertainment Meals,300,2020-10-30,Food Mobile,3500,2020-11-02,Gadgets Exam Fees,1245,2020-11-04,Academic Next, create a file expensedb.js and include code to load the initial expense data into the data store. The code checks the data store for initial data and load only if the data is not available in the store. var store = require(“nedb”) var fs = require(”fs”); var expenses = new store({ filename: “expense.db”, autoload: true }) expenses.find({}, function (err, docs) { if (docs.length == 0) { loadExpenses(); } }) function loadExpenses() { readCsv(“data.csv”, function (data) { console.log(data); data.forEach(function (rec, idx) { item = {} item.name = rec[0]; item.amount = parseFloat(rec[1]); item.spend_date = new Date(rec[2]); item.category = rec[3]; expenses.insert(item, function (err, doc) { console.log(”Inserted”, doc.item_name, ”with ID”, doc._id); }) }) }) } function readCsv(file, callback) { fs.readFile(file, ”utf-8”, function (err, data) { if (err) throw err; var lines = data.split(”rn”); var result = lines.map(function (line) { return line.split(”,”); }); callback(result); }); } module.exports = expenses Next, create a file, server.js and include the actual code to list, add, update and delete the expense entries. var express = require(“express”) var cors = require(”cors”) var expenseStore = require(“./expensedb.js”) var app = express() app.use(cors()); var bodyParser = require(“body-parser”); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); var HTTP_PORT = 8000 app.listen(HTTP_PORT, () => { console.log(“Server running on port %PORT%”.replace(“%PORT%”, HTTP_PORT)) }); app.get(“/”, (req, res, next) => { res.json({ “message”: “Ok” }) }); app.get(“/api/expenses”, (req, res, next) => { expenseStore.find({}, function (err, docs) { res.json(docs); }); }); app.get(“/api/expense/:id”, (req, res, next) => { var id = req.params.id; expenseStore.find({ _id: id }, function (err, docs) { res.json(docs); }) }); app.post(“/api/expense/”, (req, res, next) => { var errors = [] if (!req.body.item) { errors.push(“No item specified”); } var data = { name: req.body.name, amount: req.body.amount, category: req.body.category, spend_date: req.body.spend_date, } expenseStore.insert(data, function (err, docs) { return res.json(docs); }); }) app.put(“/api/expense/:id”, (req, res, next) => { var id = req.params.id; var errors = [] if (!req.body.item) { errors.push(“No item specified”); } var data = { _id: id, name: req.body.name, amount: req.body.amount, category: req.body.category, spend_date: req.body.spend_date, } expenseStore.update( { _id: id }, data, function (err, docs) { return res.json(data); }); }) app.delete(“/api/expense/:id”, (req, res, next) => { var id = req.params.id; expenseStore.remove({ _id: id }, function (err, numDeleted) { res.json({ “message”: “deleted” }) }); }) app.use(function (req, res) { res.status(404); }); Now, it is time to run the application. npm run start Next, open a browser and enter http://localhost:8000/ in the address bar. { “message”: “Ok” } It confirms that our application is working fine. Finally, change the url to http://localhost:8000/api/expense and press enter. The browser will show the initial expense entries in JSON format. [ … { “name”: “Pizza”, “amount”: 80, “spend_date”: “2020-10-10T00:00:00.000Z”, “category”: “Food”, “_id”: “5H8rK8lLGJPVZ3gD” }, … ] Let

ReactJS – Stateless Component

ReactJS – Stateless Component ”; Previous Next React component with internal state is called Stateful component and React component without any internal state management is called Stateless component. React recommends to create and use as many stateless component as possible and create stateful component only when it is absolutely necessary. Also, React does not share the state with child component. The data needs to be passed to the child component through child”s properties. An example to pass date to the FormattedDate component is as follows − <FormattedDate value={this.state.item.spend_date} /> The general idea is not to overcomplicate the application logic and use advanced features only when necessary. Create a stateful component Let us create a React application to show the current date and time. Step 1 − First, create a new react application, react-clock-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Open the application in your favorite editor. Step 2 − Create src folder under the root directory of the application. Create components folder under src folder. Create a file, Clock.js under src/components folder and start editing. Import React library. import React from ”react”; Next, create Clock component. class Clock extends React.Component { constructor(props) { super(props); } } Step 3 − Initialize state with current date and time. constructor(props) { super(props); this.state = { date: new Date() } } Step 4 − Add a method, setTime() to update the current time − setTime() { console.log(this.state.date); this.setState((state, props) => ( { date: new Date() } )) } Step 5 − Use JavaScript method, setInterval and call setTime() method every second to ensure that the component”s state is updated every second. constructor(props) { super(props); this.state = { date: new Date() } setInterval( () => this.setTime(), 1000); } Step 6 − Create a render function. render() { } Next, update the render() method to show the current time. render() { return ( <div><p>The current time is {this.state.date.toString()}</p></div> ); } Finally, export the component. export default Clock; The complete source code of the Clock component is as follows − import React from ”react”; class Clock extends React.Component { constructor(props) { super(props); this.state = { date: new Date() } setInterval( () => this.setTime(), 1000); } setTime() { console.log(this.state.date); this.setState((state, props) => ( { date: new Date() } )) } render() { return ( <div> <p>The current time is {this.state.date.toString()}</p> </div> ); } } export default Clock; index.js Next, create a file, index.js under the src folder and use Clock component. import React from ”react”; import ReactDOM from ”react-dom”; import Clock from ”./components/Clock”; ReactDOM.render( <React.StrictMode> <Clock /> </React.StrictMode>, document.getElementById(”root”) ); index.html 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>Clock</title> </head> <body> <div id=”root”></div> <script type=”text/JavaScript” src=”./index.js”></script> </body> </html> Serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. The application will show the time and update it every second. The current time is Wed Nov 11 2020 10:10:18 GMT+0530(Indian Standard Time) The above application works fine but throws an error in the console. Can”t call setState on a component that is not yet mounted. The error message indicates that the setState has to be called only after the component is mounted. What is mounting? React component has a life-cycle and mounting is one of the stages in the life cycle. Let us learn more about the life-cycle in the upcoming chapters. Introduce state in expense manager app Let us introduce state management in the expense manager application by adding a simple feature to remove an expenses item. Step 1 − Open expense-manager application in your favorite editor. Open ExpenseEntryItemList.js file. Initialize the state of the component with the expense items passed into the components through properties. this.state = { items: this.props.items } Step 2 − Add the Remove label in the render()method. <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> Step 3 − Update the lists in the render() method to include the remove link. Also, use items in the state (this.state.items) instead of items from the properties (this.props.items). const lists = this.state.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href=”#” onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td> </tr> ); Step 4 − Implement handleDelete method, which will remove the relevant expense item from the state. handleDelete = (id, e) => { e.preventDefault(); console.log(id); this.setState((state, props) => { let items = []; state.items.forEach((item, idx) => { if(item.id != id) items.push(item) }) let newState = { items: items } return newState; }) } Here, Expense items are fetched from the current state of the component. Current expense items are looped over to find the item referred by the user using id of the item. Create a new item list with all the expense item except the one referred by the user Step 5 − Add a new row to show the total expense amount. <tr> <td colSpan=”1″ style={{ textAlign: “right” }}>Total Amount</td> <td colSpan=”4″ style={{ textAlign: “left” }}> {this.getTotal()} </td> </tr> Step 6 − Implement the getTotal() method to calculate the total expense amount. getTotal() { let total = 0; for(var i = 0; i < this.state.items.length; i++) { total += this.state.items[i].amount } return total; } The complete code of the render() method

ReactJS – Building and Deployment

ReactJS – Building & Deployment ”; Previous Next Let us learn how to do production build and deployment of React application in this chapter. Building Once a React application development is done, application needs to be bundled and deployed to a production server. Let us learn the command available to build and deploy the application in this chapter. A single command is enough to create a production build of the application. npm run build > [email protected] build pathtoexpense-manager > react-scripts build Creating an optimized production build… Compiled with warnings. File sizes after gzip: 41.69 KB buildstaticjs2.a164da11.chunk.js 2.24 KB buildstaticjsmain.de70a883.chunk.js 1.4 KB buildstaticjs3.d8a9fc85.chunk.js 1.17 KB buildstaticjsruntime-main.560bee6e.js 493 B buildstaticcssmain.e75e7bbe.chunk.css The project was built assuming it is hosted at /. You can control this with the homepage field in your package.json. The build folder is ready to be deployed. You may serve it with a static server: npm install -g serve serve -s build Find out more about deployment here: https://cra.link/deployment Once the application is build, the application is available under build/static folder. By default, profiling option is disable and can be enabled through -profile command line option. -profile will include profiling information in the code. The profiling information can be used along with React DevTools to analyse the application. npm run build — –profile Deployment Once the application is build, it can be deployed to any web server. Let us learn how to deploy a React application in this chapter. Local deployment Local deployment can be done using serve package. Let us first install serve package using below command − npm install -g server To start the application using serve, use the below command − cd /go/to/app/root/folder serve -s build By default, serve serve the application using port 5000. The application can be viewed @ http://localhost:5000. Production deployment Production deployment can be easily done by copying the files under build/static folder to the production application”s root directory. It will work in all web server including Apache, IIS, Nginx, etc. Relative path By default, the production build is created assuming that the application will be hosted in the root folder of a web application. If the application needs to be hosted in a subfolder, then use below configuration in the package.json and then build the application. { … “homepage”: “http://domainname.com/path/to/subfolder”, … } Print Page Previous Next Advertisements ”;

ReactJS – JSX

ReactJS – JSX ”; Previous Next As we learned earlier, React JSX is an extension to JavaScript. It allows writing a JavaScript code that looks like an HTML code. For instance, consider the following code: const element = <h1>Hello React!</h1> The tag provided in the code above is known as JSX. JSX is mainly used to provide information about the appearance of an interface. However, it is not completely a template language but a syntax extension to JavaScript. JSX produces elements that are rendered into a DOM, in order to specify what the output must look like. Using JSX in ReactJS JSX enables the developer to create a virtual DOM using XML syntax. It compiles down to pure JavaScript (React.createElement function calls), therefore, it can be used inside any valid JavaScript code. Assign to a variable. var greeting = <h1>Hello React!</h1> Assign to a variable based on a condition. var canGreet = true; if(canGreet) { greeting = <h1>Hello React!</h1> } Can be used as return value of a function. function Greeting() { return <h1>Hello React!</h1> } greeting = Greeting() Can be used as argument of a function. function Greet(message) { ReactDOM.render(message, document.getElementById(”react-app”) } Greet(<h1>Hello React!</h1>) Why JSX? Using JSX with React is not mandatory, as there are various options to achieve the same thing as JSX; but it is helpful as a visual aid while working with UI inside a JavaScript code. JSX performs optimization while translating the code to JavaScript, making it faster than regular JavaScript. React uses components that contain both markup and logic in a single file, instead of separate files. Most of the errors can be found at compilation time, as the data flow is unidirectional. Creating templates becomes easier with JSX. We can use JSX inside of conditional statements (if−else) and loop statements (for loops), can assign it to variables, accept it as arguments, or return it from functions. Using JSX can prevent Cross Site Scripting attacks, or injection attacks. Expressions in JSX JSX supports expression in pure JavaScript syntax. Expression has to be enclosed inside the curly braces, { }. Expression can contain all variables available in the context, where the JSX is defined. Let us create simple JSX with expression. Example <script type=”text/babel”> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById(”react-app”) ); </script> Output Here, cTime used in the JSX using expression. The output of the above code is as follows, The Current time is 21:19:56 GMT+0530(India Standard Time) One of the positive side effects of using expression in JSX is that it prevents Injection attacks as it converts any string into html safe string. Functions in JSX JSX supports user defined JavaScript function. Function usage is similar to expression. Let us create a simple function and use it inside JSX. Example <script type=”text/babel”> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById(”react-app”) ); </script> Output Here, getCurrentTime() is used get the current time and the output is similar as specified below − The Current time is 21:19:56 GMT+0530(India Standard Time) Attributes in JSX JSX supports HTML like attributes. All HTML tags and its attributes are supported. Attributes has to be specified using camelCase convention (and it follows JavaScript DOM API) instead of normal HTML attribute name. For example, class attribute in HTML has to be defined as className. The following are few other examples − htmlFor instead of for tabIndex instead of tabindex onClick instead of onclick Example <style> .red { color: red } </style> <script type=”text/babel”> function getCurrentTime() { return new Date().toTimeString(); } ReactDOM.render( <div> <p>The current time is <span className=”red”>{getCurrentTime()}</span></p> </div>, document.getElementById(”react-app”) ); </script> Output The output is as follows − The Current time is 22:36:55 GMT+0530(India Standard Time) Using Expression within Attributes JSX supports expression to be specified inside the attributes. In attributes, double quote should not be used along with expression. Either expression or string using double quote has to be used. The above example can be changed to use expression in attributes. <style> .red { color: red } </style> <script type=”text/babel”> function getCurrentTime() { return new Date().toTimeString(); } var class_name = “red”; ReactDOM.render( <div> <p>The current time is <span className={class_name}>{getCurrentTime()}</span></p> </div>, document.getElementById(”react-app”) ); </script> Nested Elements in JSX Nested elements in JSX can be used as JSX Children. They are very useful while displaying the nested components. You can use any type of elements together including tags, literals, functions, expressions etc. But false, null, undefined, and true are all valid elements of JSX; they just don”t render as these JSX expressions will all render to the same thing. In this case, JSX is similar to HTML. Following is a simple code to show the usage of nested elements in JSX − <div> This is a list: <ul> <li>Element 1</li> <li>Element 2</li> </ul> </div> Print Page Previous Next Advertisements ”;

ReactJS – State Management Using React Hooks

ReactJS – State Management using React Hooks ”; Previous Next React introduces an entirely new concepts called React Hooks from React 16.8. Even though, it is a relatively new concept, it enables React functional component to have its own state and life-cycle. Also, React Hooks enables functional component to use many of the feature not available earlier. Let us see how to do state management in a functional component using React Hooks in this chapter. What is React Hooks? React Hooks are special functions provided by React to handle a specific functionality inside a React functional component. React provides a Hook function for every supported feature. For example, React provides useState() function to manage state in a functional component. When a React functional component uses React Hooks, React Hooks attach itself into the component and provides additional functionality. The general signature of useState() Hook is as follows − const [<state variable>, <state update function>] = useState(<initial value>); For example, state management in clock component using Hooks can be done as specified below − const [currentDateTime, setCurrentDateTime] = useState(new Date()); setInterval(() => setCurrentDateTime(new Date()), 1000); Here, currentDateTime − Variable used to hold current date and time (returned by setState() setCurrentDate() − Function used to set current date and time (returned by setState()) Create a stateful component Let us recreate our clock component using Hooks in this chapter. Step 1 − First, create a new react application, react-clock-hook-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Step 2 − Open the application in your favorite editor. Create src folder under the root directory of the application. Create components folder under src folder. Create a file, Clock.js under src/components folder and start editing. Import React library and React state Hook, setState. import React, { useState } from ”react”; Step 2 − Create Clock component. function Clock() { } Create state Hooks to maintain date and time. const [currentDateTime, setCurrentDateTime] = useState(new Date()); Set date and time for every second. setInterval(() => setCurrentDateTime(new Date()), 1000); Create the user interface to show the current date and time using currentDateTime and return it. return ( <div><p>The current time is {currentDateTime.toString()}</p></div> ); Step 3 − Finally, export the component using the code snippet − export default Clock; The complete source code of the Clock component is as follows − import React, { useState } from ”react”; function Clock(props) { const [currentDateTime, setCurrentDateTime] = useState(new Date()); setInterval(() => setCurrentDateTime(new Date()), 1000); return ( <div><p>The current time is {currentDateTime.toString()}</p></div> ); } export default Clock; index.js: Next, create a file, index.js under the src folder and use Clock component. import React from ”react”; import ReactDOM from ”react-dom”; import Clock from ”./components/Clock”; ReactDOM.render( <React.StrictMode> <Clock /> </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>Clock</title> </head> <body> <div id=”root”></div> <script type=”text/JavaScript” src=”./index.js”></script> </body> </html> Then, serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. The application will show the time and update it every second. The current time is Wed Nov 11 2020 10:10:18 GMT+0530 (India Standard Time) The above application works fine. But, setCurrentDateTime() set to execute every second has to be removed when the application ends. We can do this using another Hook,useEffect provided by React. We will learn it in the upcoming chapter (Component life cycle). Introducing state in expense manager app Let us introduce state management in the expense manager application by adding a simple feature to remove an expenses item using Hooks in this chapter. Step 1 − Open expense-manager application in your favorite editor. Create a new file, ExpenseEntryItemListFn.js under src/components folder and start editing. Import React library and React state Hook, setState. import React, { useState } from ”react”; Import the css, ExpenseEntryItem.css. import ”./ExpenseEntryItemList.css” Step 2 − Create ExpenseEntryItemListFn component. function ExpenseEntryItemListFn(props) { } Initialize the state Hooks of the component with the expense items passed into the components through properties. const [items, setItems] = useState(props.items); Step 3 − Create event handlers to highlight the rows. function handleMouseEnter(e) { e.target.parentNode.classList.add(“highlight”); } function handleMouseLeave(e) { e.target.parentNode.classList.remove(“highlight”); } function handleMouseOver(e) { console.log(“The mouse is at (” + e.clientX + “, ” + e.clientY + “)”); } Step 4 − Create event handler to remove the selected items using items and setItems(). function handleDelete(id, e) { e.preventDefault(); console.log(id); let newItems = []; items.forEach((item, idx) => { if (item.id != id) newItems.push(item) }) setItems(newItems); } Step 5 − Create getTotal() method to calculate the total amount. function getTotal() { let total = 0; for (var i = 0; i < items.length; i++) { total += items[i].amount } return total; } Step 6 − Create user interface to show the expenses by looping over the items. const lists = items.map((item) => <tr key={item.id} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href=”#” onClick={(e) => handleDelete(item.id, e)}>Remove</a></td> </tr> ); Step 7 − Create the complete UI to show the expenses and return it. return ( <table onMouseOver={handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} <tr> <td colSpan=”1″ style={{ textAlign: “right” }}>Total Amount</td> <td colSpan=”4″ style={{ textAlign: “left” }}> {getTotal()} </td> </tr> </tbody> </table> ); Finally, export the function as shown below − export default ExpenseEntryItemListFn; The complete code of the ExpenseEntryItemListFn is as follows − import

ReactJS – Introduce Events in Expense Manager APP

Introduce Events in Expense Manager APP ”; Previous Next In the previous chapters, we have learned that events are just some actions performed by a user to interact with any application. They can be the smallest of actions, like hovering a mouse pointer on an element that triggers a drop-down menu, resizing an application window, or dragging and dropping elements to upload them etc. For each of these events, JavaScript provides responses. So, every time an event is performed by the user, it usually requires some type of reaction from the application; and these reactions are defined as some functions or blocks of code, called Event Handlers. To understand event handling better, let us try to introduce events into an example application (Expense Manager APP). In this chapter we are trying to handle Mouse Events in the expense manager app. Mouse events are just some actions performed by users using mouse. These include hovering, clicking, dragging or simply any action that can be performed on an application using a mouse. Handling Events in Expense Manager APP Let us do some event management in our expense application. We can try to highlight the expense entry item in the table when the user moves the cursor over it. Step 1 − Open expense-manager application in your favorite editor. Open ExpenseEntryItemList.js file and add a method handleMouseEnter to handle the event fired (onMouseEnter) when the user moves the mouse pointer into the expense items (td – table cell). handleMouseEnter(e) { e.target.parentNode.classList.add(“highlight”); } Here, Event handler tries to find the parent node (tr) of the event target (td) node using parentNode method. The parentNode method is the standard DOM method to find the immediate parent the current node. Once the parent node is found, event handler access the list of the css class attached to the parent node and adds ”highlight” class using add method. classList is the standard DOM property to get list of class attached to the node and it can be used to add / remove class from a DOM node. Step 2 − Next, add a method, handleMouseLeave() to handle the event fired when the user moves out of the expense item. handleMouseLeave(e) { e.target.parentNode.classList.remove(“highlight”); } Here, Event handler removes the highlight class from the DOM. Add another method, handleMouseOver() to check where the mouse is currently positioned. It is optional to find the where about of the mouse pointer in the DOM. handleMouseOver(e) { console.log(“The mouse is at (” + e.clientX + “, ” + e.clientY + “)”); } Step 3 − Bind all event handlers in the constructor of the component. this.handleMouseEnter = this.handleMouseEnter.bind(); this.handleMouseLeave = this.handleMouseLeave.bind(); this.handleMouseOver = this.handleMouseOver.bind(); Step 4 − Attach the event handlers to the corresponding tag in the render method. render() { const lists = this.props.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> </tr> ); return ( <table onMouseOver={this.handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> </tr> </thead> <tbody> {lists} </tbody> </table> ); } The final and complete code of the ExpenseEntryItemList is as follows − import React from ”react”; import ”./ExpenseEntryItemList.css”; class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); this.handleMouseEnter = this.handleMouseEnter.bind(); this.handleMouseLeave = this.handleMouseLeave.bind(); this.handleMouseOver = this.handleMouseOver.bind(); } handleMouseEnter(e) { e.target.parentNode.classList.add(“highlight”); } handleMouseLeave(e) { e.target.parentNode.classList.remove(“highlight”); } handleMouseOver(e) { console.log(“The mouse is at (” + e.clientX + “, ” + e.clientY + “)”); } render() { const lists = this.props.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> </tr> ); return ( <table onMouseOver={this.handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> </tr> </thead> <tbody> {lists} </tbody> </table> ); } } export default ExpenseEntryItemList; ExpenseEntryItemList.css: Next, open the css file, ExpenseEntryItemList.css and add a css class, highlight. tr.highlight td { background-color: #a6a8bd; } index.js Open index.js and use the ExpenseEntryItemList component. import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItemList from ”./components/ExpenseEntryItemList” const items = [ { id: 1, name: “Pizza”, amount: 80, spendDate: “2020-10-10”, category: “Food” }, { id: 2, name: “Grape Juice”, amount: 30, spendDate: “2020-10-12”, category: “Food” }, { id: 3, name: “Cinema”, amount: 210, spendDate: “2020-10-16”, category: “Entertainment” }, { id: 4, name: “Java Programming book”, amount: 242, spendDate: “2020-10-15”, category: “Academic” }, { id: 5, name: “Mango Juice”, amount: 35, spendDate: “2020-10-16”, category: “Food” }, { id: 6, name: “Dress”, amount: 2000, spendDate: “2020-10-25”, category: “Cloth” }, { id: 7, name: “Tour”, amount: 2555, spendDate: “2020-10-29”, category: “Entertainment” }, { id: 8, name: “Meals”, amount: 300, spendDate: “2020-10-30”, category: “Food” }, { id: 9, name: “Mobile”, amount: 3500, spendDate: “2020-11-02”, category: “Gadgets” }, { id: 10, name: “Exam Fees”, amount: 1245, spendDate: “2020-11-04”, category: “Academic” } ] ReactDOM.render( <React.StrictMode> <ExpenseEntryItemList items={items} /> </React.StrictMode>, document.getElementById(”root”) ); Serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. The application will respond to mouse events and highlight the currently selected row. Item Amount Date Category Pizza 80 Sat Oct 10 2020 Food Grape Juice 30 Man Oct 12 2020 Food Cinema 210 Fri Oct 16 2020 Entertainment Java Programming book 242 Thu Oct 15 2020 Academic Mango Juice 35 Fri Oct 16 2020 Food Dress 2000 Sun Oct 25 2020 Cloth Tour 2555 Thu Oct 29 2020 Entertainment Meals 300 Fri Oct 30 2020 Food Mobile 3500 Mon Nov 02 2020 Gadgets