ReactJS – Keys

ReactJS – Keys ”; Previous Next List and keys We learned how to use collections in React using for loop and map function in previous chapters. If we run the application, it output as expected. If we open the developer console in the browser, then it will show a warning as shown below − Warning: Each child in a list should have a unique “key” prop. Check the render method of `ExpenseListUsingForLoop`. See https://reactjs.org/link/warning-keys for more information. tr ExpenseListUsingForLoop@ div App So, what does it means and how it affects our React application. As we know, React tries to render only the updated values in DOM through various mechanism. When the React renders a collection, it tries to optimize the rendering by updating only the updated item in the list. But, there is no hint for the React to find which items are new, updated or removed. To get the information, React allows a key attributes for all components. The only requirement is that the value of the key should be unique among the current collection. Let us recreate one of our earlier application and apply the key attributes. 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. Then, 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. Then, add expense items and total amount in the render method. render() { var items = this.props[”expenses”]; var expenses = [] expenses = items.map((item, idx) => <tr key={idx}><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, 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. Set the key attributes for each row with the index value of the item. 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 key={idx}><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; } Next, check the application in the browser. It will show the expenses as shown below − Finally, open the developer console and find that the warning about key is not shown. Key and index We learned that the key should be unique to optimize the rendering of the component. We used index value and the error is gone. Is it still correct way to provide value for the list? The answer is Yes and No. Setting the index key will work in most situation but it will behave in unexpected ways if we use uncontrolled component in our application. Let us update our application and add two new features as specified below − Add an input element to each row adjacent to expense amount. Add a button to remove the first element in the list. First of all, add a constructor and set the initial state of the application. As we are going to remove certain item during runtime of our application, we should use state instead of props. constructor(props) { super(props) this.state = { expenses: this.props[”expenses”] } } Next, add a function to remove the first element of the list. remove() { var itemToRemove = this.state[”expenses”][0] this.setState((previousState) => ({ expenses: previousState[”expenses”].filter((item) => item != itemToRemove) })) } Next, bind the remove function in the constructor as shown below − constructor(props) { super(props) this.state = { expenses: this.props[”expenses”] } this.remove = this.remove.bind(this) } Next, add a button below the table and set remove function in its onClick action. render() { var items = this.state[”expenses”]; var expenses = [] expenses = items.map( (item, idx) => <tr key={idx}><td>item {idx + 1}</td><td>{item}</td></tr>) var total = this.getTotalExpenses(); return ( <div> <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> <div> <button onClick={this.remove}>Remove first item</button> </div> </div>

ReactJS – Strict Mode

ReactJS – Strict Mode ”; Previous Next React is build on the concept of component, properties and state. React provides a relatively few set of API to create and update components. The basic features of React is enough for large part of the our front end application. But, still modern application has complex scenarios, which needs advanced front-end logic. React provides lot of high-level API, which will help us to create complex front-end application. The high-level API comes with a cost. High-level API are little bit tough to learn and apply it in our application. React provides a strict mode, which helps the developer to properly apply the high-level API by highlighting the potential problem during development phase of our application. As we know, everything in the React is build on the concept of components, strict mode is simply a non-visual component, React.StrictMode. The usage of strict mode component is also very simple. Just wrap the component to be analyzed with React.StrictMode component as shown below − <React.StrictMode> <OurComplexComponent /> </React.StrictMode> Another functionality of the strict mode is to throw error or warning when certain legacy or depreciated API (which will eventually introduce bugs in the application) are used in the application. Let us learn the list of items highlighted by strict mode component in this chapter. Unsafe lifecycle usage React identifies some of the legacy lifecycle events are unsafe to use in the async based application. They are as follows − componentWillMount componentWillReceiveProps componentWillUpdate Unsafe means it will create hard to debug bugs in the application. React will eventually remove these unsafe lifecycle event in the future version of the library. Until then, developer are alerted when they use legacy unsafe lifecycle events. Legacy ref API usage Earlier version of React uses string based ref management and later added callback based ref management. The recommended way is to use callback based option due to its stability and less error-prone nature. Strict mode will throw warning if we use string based option. The most recent version of React provides improved ref management option, which is both easy to code and less error-prone nature. Legacy findDOMNode usage findDOMNode helps to search the tree of DOM node given a class instance. The usage of findDOMNode is depreciated and promotes the usage of ref based DOM management. Side effects React has two major phases, render and commit. render phase involves major work and time-consuming and commit phase is straight forward and fast. React introduces a concurrent mode, which will improve the performance of the render phase. One of the requirement of the concurrent mode is that the lifecycle event used in the render phase should not contain side effects. React will try to find the unexpected side effects using different approaches during development phase and report it as warning. Legacy context API Legacy context API is error-prone and it is not recommended to use. It will be removed in the future version. Until then, strict mode will detect the usage of legacy context API and report it. Reusable state Components with reusable state can be mounted and destroyed multiple time without any side effects and will help to improve the performance of the application. The future version of the React library will add or remove section of UI while preserving state. React 18 introduces a strict mode feature, which will try to unmount and remount the component to ensure the component is resilient. Any issue during this phase will be reported. Print Page Previous Next Advertisements ”;

ReactJS – Inline Style

ReactJS – Inline Style ”; Previous Next React provides a unique way of directly writing the CSS in the react component and using it inside JSX. The concept is called CSS in JS and provides many advantages over traditional usage of styles. Let us learn what is inline styling and how to use it react component. Concept of inline styling CSS enables the developer to design the UI of the web application. React provides first class support for CSS and allows CSS to be imported directly into the react application. Directly importing CSS into a react component is as simple as importing a package. import ”./App.css” But, importing css directly into the web component has one major disadvantage, Global namespace. Global style may affect the style of an individual component if there is a conflict in the class name. Developer need to be careful to assign some prefix to make sure that the conflict will not happen. The other way around is to allow the Javascript to manage the CSS and it is called CSS in JS. React allows the CSS to be used inside the JSX through special CSS syntax. React provides a style props for every component, which can be used specify inline style. The inline style should be provided in a Javascript object. The object should follows the below mentioned rules, The object key should be CamelCased version of normal CSS attributes. For example, the background-color should be specified as backgroundColor. { backgroundColor: “red” } The object value should be one of the allowed values of the corresponding object key in CSS and should be in string format. For example, the font-size CSS attributes and its value (12px) should be specified as follows − { fontSize: “12px” } React will handle the conflict and render the application correctly. Applying inline style Let us learn how to apply inline style in a react application 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 the CSS classes. // remove the css Next, create a simple component, SimpleStyle (src/Components/SimpleIcon.js) as shown below − import React from “react”; class SimpleStyle extends React.Component { displayStyle = { fontFamily: ”Times New Roman”, fontSize: “24px”, color: “red” } render() { return ( <div> <div style={this.displayStyle}> Sample text to understand inline style (object as variable) in React component </div> <hr /> <div style={{ fontFamily: ”Arial”, fontSize: “24px”, color: “grey”}}> Sample text to understand inline style (object as expression) in React component </div> </div> ) } } export default SimpleStyle Here we have, Styled the first div using variable (displayStyle). Styled the second div using expression. Next, open App component (src/App.js) and update the content with SimpleStyle component as shown below − import ”./App.css” import React from ”react”; import SimpleStyle from ”./Components/SimpleStyle” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleStyle /> </div> </div> </div> ); } export default App; Here we have, Imported the SimpleStyle component. Used SimpleStyle component to render the calender icon. Finally, open the application in the browser. The content will be rendered as shown below − Summary Inline styling helps developer to quickly include the CSS style without worrying about the conflict of the CSS styles. Also, the syntax is very similar to CSS and it makes it easy for the developer to use the feature without much learning curve. Print Page Previous Next Advertisements ”;

ReactJS – Pagination

ReactJS – Pagination ”; Previous Next React provides pagination component through third party UI component library. React community provides a large collection of UI / UX components and it is tough to choose the right library for our requirement. Bootstrap UI library is one of the popular choice for the developer and it is extensively used. React Bootstrap (https://react-bootstrap.github.io/) has ported almost all the bootstrap UI components and it has best support for Pagination component as well. Let us learn how to use Pagination component from react-bootstrap library in this chapter. Pagination component Pagination component allows the developer to create simple pagination with bootstrap design in a web application. Pagination component accepts below components. Pagination.Item Pagination.First Pagination.Last Pagination.Previous Pagination.Next Pagination component accepts a small set of props to customize the pagination component and they are as follows − size (sm | lg) Set the size of the pagination buttons bsPrefix (string) Enables to change the underlying component CSS Pagination.Item component accepts a small set of props to customize the pagination component and they are as follows − active (boolean) Set the item as active one and don”t render a tag. activeLabel (string) Label to indicate the state of the pagination item disabled (boolean) Disable the pagination item href (string) Link for the pagination item onClick (function) Callback function to be called when onClick event is fired Applying Pagination component 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 react-bootstrap Next, open App.css (src/App.css) and remove all the CSS classes. // remove the css Next, create a simple pagination component, SimplePagination (src/Components/SimplePagination.js) as shown below − import React from ”react”; import { Table, Pagination } from ”react-bootstrap”; class SimplePagination extends React.Component { render() { <div>Pagination component</div> } } export default SimplePagination; 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”, “age”:22 }, { “id”:54, “name”:”Merci”, “age”:21 }, { “id”:55, “name”:”Mitchel”, “age”:30 }, { “id”:56, “name”:”Clari”, “age”:18 }, { “id”:57, “name”:”Laurena”, “age”:19 }, { “id”:58, “name”:”Odessa”, “age”:30 }, { “id”:59, “name”:”Pippy”, “age”:25 }, { “id”:60, “name”:”Wilmar”, “age”:23 }, { “id”:61, “name”:”Cherianne”, “age”:24 }, { “id”:62, “name”:”Huberto”, “age”:25 }, { “id”:63, “name”:”Ariella”, “age”:26 }, { “id”:64, “name”:”Lorant”, “age”:30 }, { “id”:65, “name”:”Francesca”, “age”:25 }, { “id”:66, “name”:”Ingamar”, “age”:28 }, { “id”:67, “name”:”Myrta”, “age”:27 }, { “id”:68, “name”:”Nicolette”, “age”:26 }, { “id”:69, “name”:”Petra”, “age”:22 }, { “id”:70, “name”:”Cyrill”, “age”:27 }, { “id”:71, “name”:”Ad”, “age”:23 }, { “id”:72, “name”:”Denys”, “age”:22 }, { “id”:73, “name”:”Karilynn”, “age”:23 }, { “id”:74, “name”:”Gunner”, “age”:30 }, { “id”:75, “name”:”Falkner”, “age”:20 }, { “id”:76, “name”:”Thurston”, “age”:19 }, { “id”:77, “name”:”Codi”, “age”:30 }, { “id”:78, “name”:”Jacob”, “age”:31 }, { “id”:79, “name”:”Gasparo”, “age”:26 }, { “id”:80, “name”:”Mitzi”, “age”:29 }, { “id”:81, “name”:”Rubetta”, “age”:21 }, { “id”:82, “name”:”Clary”, “age”:20 }, { “id”:83, “name”:”Oliviero”, “age”:24 }, { “id”:84, “name”:”Ranique”, “age”:21 }, { “id”:85, “name”:”Shae”, “age”:24 }, { “id”:86, “name”:”Woodrow”, “age”:20 }, { “id”:87, “name”:”Junia”, “age”:31 }, { “id”:88, “name”:”Athene”, “age”:26 }, { “id”:89, “name”:”Veriee”, “age”:18 }, { “id”:90, “name”:”Rickie”, “age”:30 }, { “id”:91, “name”:”Carly”, “age”:23 }, { “id”:92, “name”:”Vern”, “age”:19 }, { “id”:93, “name”:”Trix”, “age”:26 }, { “id”:94, “name”:”Lenore”, “age”:20 }, { “id”:95, “name”:”Hanna”, “age”:30 }, { “id”:96, “name”:”Dominique”, “age”:21 }, { “id”:97, “name”:”Karlotta”, “age”:22 }, { “id”:98, “name”:”Levey”, “age”:20 }, { “id”:99, “name”:”Dalila”, “age”:18 }, { “id”:100, “name”:”Launce”, “age”:21 } ] Next, add a constructor in the SimplePagination component and set initial state as shown below − constructor(props) { super(props); this.state = { users: [], usersToBeShown: [], currentPage: 1 } }; Next, add componentDidMount lifecycle event and add below code to fetch and process the user information. componentDidMount() { fetch(”users.json”) .then((response) => response.json()) .then((data) => { // console.log(data); this.setState({ users: data, pageSize: 3, usersToBeShown: [], pageArray: [] }); this.calculatePaginationDetails(1) }); } Next, implement the pagination logic in the calculatePaginationDetails method as shown below − calculatePaginationDetails = (page) => { console.log(page) let users = this.state.users; let total = users.length; let pages = Math.floor((users.length / this.state.pageSize) + 1); let firstPage = 1;

ReactJS – Helmet

ReactJS – Helmet ”; Previous Next The meta information of a web document is very important for SEO purposes. The meta information of a document is generally specified inside the head using meta tag. title tag also plays an important role in providing meta information about a document. Head section will have script and style tags as well. Helmet component provides an easy way to manage the head section of a document by providing all valid head tags. Helmet will gather all the information specified inside it and update the head section of the document. Let us learn how to use Helmet component in this chapter. Installing Helmet Before going through the concept and usage of helmet, let us learn how to install the helmet component using npm command. npm install –save react-helmet The above command will install the helmet component and will be ready to use in our application. Concept and usage of Helmet Helmet accepts all valid head tags. It accepts the plain HTML tags and output the tags in the head section of the document as shown below − import React from “react”; import {Helmet} from “react-helmet”; class Application extends React.Component { render () { return ( <div className=”application”> <Helmet> <title>Helmet sample application</title> <meta charSet=”utf-8″ /> <meta name=”description” content=”Helmet sample program to understand the working of the helmet component” /> <meta name=”keywords” content=”React, Helmet, HTML, CSS, Javascript” /> <meta name=”author” content=”Peter” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> </Helmet> // … </div> ); } }; Here, title is used to specify the title to the document description meta tag is used to specify the details of the document keywords is used to specify the main keywords of the document. It will be used by search engine. author is used to specify the author of the document viewport is used to specify the default view port of the document charSet is used to specify the character set used in the document. The output of the head section will be as follows − <head> <title>Helmet sample application</title> <meta charSet=”utf-8″ /> <meta name=”description” content=”Helmet sample program to understand the working of the helmet component” /> <meta name=”keywords” content=”React, Helmet, HTML, CSS, Javascript” /> <meta name=”author” content=”Peter” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> </head> Helmet component can be used inside any other react component to change the header section. It can also be nested so that the header section will change when the child component is rendered. <Parent> <Helmet> <title>Helmet sample application</title> <meta charSet=”utf-8″ /> <meta name=”description” content=”Helmet sample program to understand the working of the helmet component” /> <meta name=”keywords” content=”React, Helmet, HTML, CSS, Javascript” /> <meta name=”author” content=”Peter” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> </Helmet> <Child> <Helmet> <title>Helmet sample application :: rendered by child component</title> <meta name=”description” content=”Helmet sample program to explain nested feature of the helmet component” /> </Helmet> </Child> </Parent> Here, Helmet in the child component will update the head section as below, <head> <title>Helmet sample application :: rendered by child component</title> <meta charSet=”utf-8″ /> <meta name=”description” content=”Helmet sample program to explain nested feature of the helmet component” /> <meta name=”keywords” content=”React, Helmet, HTML, CSS, Javascript”> <meta name=”author” content=”Peter”> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> </head> Applying Helmet Let us create a new react application to learn how to apply Helmet 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 component, SimpleHelmet (src/Components/SimpleHelmet.js) and render a − import React from “react”; import {Helmet} from “react-helmet”; class SimpleHelmet extends React.Component { render() { return ( <div> <Helmet> <title>Helmet sample application</title> <meta charSet=”utf-8″ /> <meta name=”description” content=”Helmet sample program to understand the working of the helmet component” /> <meta name=”keywords” content=”React, Helmet, HTML, CSS, Javascript” /> <meta name=”author” content=”Peter” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> </Helmet> <p>A sample application to demonstrate helmet component.</p> </div> ) } } export default SimpleHelmet; Here we have, Imported Helmet from the react-helmet package Used Helmet in the component to update the head section. Next, open App component (src/App.js), and use SimpleHelmet component as shown below − import ”./App.css” import React from ”react”; import SimpleHelmet from ”./Components/SimpleHelmet” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleHelmet /> </div> </div> </div> ); } export default App; Here we have, Imported SimpleHelmet component from the react package Used SimpleHelmet component Next, open index.html (public/index.html) file and remove the meta tags 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” /> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div style=”padding: 10px;”> <div id=”root”></div> </div> </body> </html> Here, title tag is removed meta tag for description, theme-color and viewport are removed Finally, open the application in the browser and check the final result. Open the source code in the dev tools and you can see the html information as shown below − <title>Helmet sample application</title> <meta charset=”utf-8″ data-react-helmet=”true”> <meta name=”description” content=”Helmet sample program to understand the working of the helmet component” data-react-helmet=”true”> <meta name=”keywords” content=”React, Helmet, HTML, CSS, Javascript” data-react-helmet=”true”> <meta name=”author” content=”Peter” data-react-helmet=”true”> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ data-react-helmet=”true”> Summary Helmet component is an easy to use component to manage the head content of the document supporting both server side and client side rendering. Print Page Previous Next Advertisements ”;

ReactJS – Context

ReactJS – Context ”; Previous Next Context is one of the important concept in React. It provides the ability to pass a information from the parent component to all its children to any nested level without passing the information through props in each level. Context will make the code more readable and simple to understand. Context can be used to store information which does not change or have minimal change. Some of the use cases of context are as follows − Application configuration Current authenticated user information Current user setting Language setting Theme / Design configuration by application / users Let us learn how to create context and its usage in this chapter. How context works? Let us learn the basic concept of context and how it works. Context has four parts, Creating a new context Setting context provider in the root component Setting context consumer in the component where we need the context information Accessing context information and using it in render method Let us create an application to better understand context and its usage. Let us create a global context for maintaining theme information in the application root component and use it in our child component. First of all, create and start an application using below command, create-react-app myapp cd myapp npm start Next, create a component, HelloWorld under components folder (src/components/HelloWorld.js) import React from “react”; import ThemeContext from “../ThemeContext”; class HelloWorld extends React.Component { render() { return <div>Hello World</div> } } export default HelloWorld Next, create with a new context (src/ThemeContext.js) for maintaining theme information. import React from ”react” const ThemeContext = React.createContext({ color: ”black”, backgroundColor: ”white” }) export default ThemeContext Here, A new context is created using React.createContext. Context is modeled as an object having style information. Set initial value for color and background of the text. Next, update the root component, App.js by including HelloWorld component and the theme provider with initial value for the theme context. import ”./App.css”; import HelloWorld from ”./components/HelloWorld”; import ThemeContext from ”./ThemeContext” function App() { return ( <ThemeContext.Provider value={{ color: ”white”, backgroundColor: ”green” }}> <HelloWorld /> </ThemeContext.Provider> ); } export default App; Here, the ThemeContext.Provider is used, which is a non-visual component to set the value of the theme context to be used in all its children component. Next, include a context consumer in HelloWorld component and style the hello world message using theme information in HelloWorld component. import React from “react”; import ThemeContext from “../ThemeContext”; class HelloWorld extends React.Component { render() { return ( <ThemeContext.Consumer> {({color, backgroundColor} ) => (<div style={{ color: color, backgroundColor: backgroundColor }}> Hello World </div>) } </ThemeContext.Consumer> ) } } export default HelloWorld Here, Used ThemeContext.Consumer, which is a non-visual component providing access to the current theme context details Used a function expression to get the current context information inside ThemeContext.Consumer Used object deconstruction syntax to get the theme information and set the value in color and backgroundColor variable. Used the theme information to style the component using style props. Finally, open the browser and check the output of the application Summary Context reduces the complexity of maintaining global data in a react application. It provides a clean concept of provider and consumer and simplifies the implementation of context. Print Page Previous Next Advertisements ”;

ReactJS – props Validation

ReactJS – props Validation ”; Previous Next One of the time consuming process in a program is to find the root cause of a bug. In react, props are used extensively. Props of a component will have different source of origin. Some component will have static props, while some component will have dynamic props coming from immediate parent component. One of the source of bugs is that the value of the props does not match the type of the props designed by the developer. This mismatch create a lot of bugs. React provides a lot of option to fix this and one such feature is PropTypes and its validation. We will learn what is PropTypes and how to use it to create a bug free react application in this chapter. PropTypes React community provides a special package, prop-types to address the properties type mismatch problem. prop-types allows the properties of the component to be specified with type through a custom setting (propTypes) inside the component. For example, properties with number type can specified using PropTypes.number option as shown below. Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number } Once the type of the properties is specified, then the React will throw warning during the development phase of the application. Let us include propTypes in our application and see how it helps to catch properties type mismatch issue. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, install prop-types package using node package manager (npm) as shown below − npm i prop-types –save Next, open App.css (src/App.css) and remove all the CSS classes. Then, create a simple component, Sum (src/Components/Sum.js) as shown below − import React from ”react” import PropTypes from ”prop-types” class Sum extends React.Component { render() { return <p>The sum of {this.props.num1} and {this.props.num2} is {parseInt(this.props.num1) + parseInt(this.props.num2)}</p> } } Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number } export default Sum Here, Purpose of the component is to find sum value of the given props (num1 and num2) and show it in the front end. Set the data type of the num1 and num2 as numbers (PropTypes.number) using propTypes. Next, open App component (src/App.js), import the bootstrap css and render the date picker as shown below − import ”./App.css” import Sum from ”./Components/Sum” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Sum num1=”10″ num2=”John” /> </div> </div> </div> ); } export default App; Here, we have rendered the Sum component with 10 and John as props Finally, open the application in your favorite browser and open the JavaScript console through developer tools. JavaScript throws the warning that the unexpected type is provided as shown below. propTypes only works during development phase to nullify the performance reduction of the application due to additional checking of the props types. This will not affect the performance of the application in production / live setup. Available validators The prop-types supplies a good collection of ready-made validators. They are as follows − PropTypes.array PropTypes.bigint PropTypes.bool PropTypes.func PropTypes.number PropTypes.object PropTypes.string PropTypes.symbol PropTypes.node – Anything that can be rendered PropTypes.element – React component PropTypes.elementType – Type of React component PropTypes.instanceOf() – instance of the specified class propTypes.oneOf([”Value1”, ”valueN”]) – one of Value and ValueN PropTypes.oneOfType([]) – Example, PropTypes.oneOfType([PropTypes.number, PropTypes.bigint]) PropTypes.arrayOf() – Example, PropTypes.arrayOf(PropTypes.number) PropTypes.objectOf() – Example, PropTypes.objectOf(PropTypes.number) PropTypes.func.isRequired propTypes.element.isRequired PropTypes.any.isRequired Custom validator A custom validator can also be created and used to validate the property”s value. Let us consider that the component have a email property and the value should be a valid email address. Then, a validate function can be written and attached to the email property as shown below − Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number, email: function(myProps, myPropName, myComponentName) { if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(myProps[myPropName])) { return new Error( ”Invalid prop value `” + myProps[myPropName] + ”` supplied to” + ” `” + myComponentName + ”/” + myPropName + ”`. Validation failed.” ); } } } Here, /^[^s@]+@[^s@]+.[^s@]+$/ is a simple regex email pattern. myProps represents all properties. myPropName represent the current property being validated. myComponentName represent the name of the component being validated. Similarly, custom validator can be created and used for array and object properties using below function signature − PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) { … }) Here, propValue represents array / object value. key represents the key of the current item. componentName represents the name of the component. propFullName represents the name of the property being validated. Summary Props types is one of the good tool for the developer to write bug free software. It will definitely help the developer to code faster and safer. Print Page Previous Next Advertisements ”;

ReactJS – Higher Order Components

ReactJS – Higher-Order Components ”; Previous Next Since react components are interconnected by composition (having one component inside another) rather than by inheritance, logic used in a react component will not be shared to an another component directly. React community provides multiple option to share the logic between components and one such option is Higher Order Component. HOC is not react api, per se, but a design pattern with no side effects. Let us learn how to use Higher Order Component in this chapter. How to use Higher Order Component Basically, HOC is a function that takes a react component as input and then create a new react component based on the input component and return the newly created (wrapped) component. For example, HOC function may receive a pure data rendering component as input, then return a new component, which will have data fetching capabilities & data rendering capabilities using input component. Let us see how to use HOC and share logic between two component in the step by step manner. Let us consider the scenario of fetching and rendering the data from an external URL. Create a HOC function with one or more input parameters depending on the functionality. The first parameter to the HOC function should be a react component with secondary logic (For example, data rendering logic). The second parameter to the HOC function should be defined as per our requirement. For our data fetching scenario, the data url is the necessary information for fetching the data. So, we should include it as second parameter of our HOC function. function createHOC(WrappedComponent, url) { // create new component using WrappedComponent } Any number of parameter is fine for HOC function, if it is indeed necessary. Create a new component inside the HOC function supporting primary logic (For example, data fetching logic using second url parameter) in it”s componentDidMount event. function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { componentDidMount() { fetch(url) .then((response) => response.json()) .then((data) => { this.setState({ data: data }); }); } } } Render the input component by passing the data fetched from componentDidMount event. function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { render() { return ( <WrappedComponent data={this.state.data} {…this.props} /> ) } } } Return the newly created component. function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { } return DataFetcher; } Create a new component by combining DataFetcher (createFetchHOC) and Wrapped component. const UserListWithFetch = createFetchHOC( UserList, “users.json” ); Finally, use the new component in any place as you wish <UserListWithFetch /> Applying HOC component Let us create a new application by applying the HOC component. 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 new HOC function as shown below − import React from ”react”; function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidMount() { fetch(url) .then((response) => response.json()) .then((data) => { this.setState({ data: data }); }); } render() { return ( <WrappedComponent data={this.state.data} {…this.props} /> ) } } return DataFetcher; } export default createFetchHOC; Next, create a file, users.json (public/users.json) in the public folder to store user information. We will try to fetch it using FetchRenderProps component and show it in our application. [{“id”:1,”name”:”Fowler”,”age”:18}, {“id”:2,”name”:”Donnell”,”age”:24}, {“id”:3,”name”:”Pall”,”age”:26}] Next, create a file, todo_list.json (public/todo_list.json) in the public folder to store todo list information. We will try to fetch it using FetchRenderProps component and show it in our application. [{“id”:1,”title”:”Learn JavaScript”,”is_done”:true}, {“id”:2,”title”:”Learn React”,”is_done”:true}, {“id”:3,”title”:”Learn Typescript”,”is_done”:false}] Next, Create a new component, UserList (src/Components/UserList.js) to render users as shown below − import React from “react”; class UserList extends React.Component { constructor(props) { super(props); } render() { return ( <> <ul> {this.props.data && this.props.data.length && this.props.data.map((item) => <li key={item.id}>{item.name}</li> )} </ul> </> ) } } export default UserList; Here, we have used the data props to render the user list Next, create a new component, TodoList (src/Components/TodoList.js) to render todos as shown below − import React from “react”; class TodoList extends React.Component { constructor(props) { super(props); this.todos = this.props.data } render() { return ( <> <ul> {this.props.data && this.props.data.length && this.props.data.map( (item) => <li key={item.id}>{item.title} {item.is_done && <strong>Done</strong>}</li> )} </ul> </> ) } } export default TodoList; Here, we have used the data props to render the todo list. Next, create a new component, SimpleHOC to render both user list and todo list through single HOC component. import React from “react”; import UserList from “./UserList”; import TodoList from “./TodoList”; import createFetchHOC from “./createFetchHOC”; const UserListWithFetch = createFetchHOC( UserList, “users.json” ); const TodoListWithFetch = createFetchHOC( TodoList, “todo_list.json” ); class SimpleHOC extends React.Component { constructor(props) { super(props); } render() { return ( <> <UserListWithFetch /> <TodoListWithFetch /> </> ) } } export default SimpleHOC; Here we have, Created UserListWithFetch component by combining TodoList and DataFetcher component. Created TodoListWithFetch component by combining Users and DataFetcher component. Next, open App.js and update it with SimpleHOC component. import ”./App.css” import React from ”react”; import SimpleHOC from ”./Components/SimpleHOC” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleHOC /> </div> </div> </div> ); } export default App; Finally, open the application in the browser and check the final result. The application will render as shown below − Summary Higher Order Component is an efficient method to share logic between components. It is extensively used in many third party component with good success

ReactJS – Creating Components using Properties

ReactJS – Create a Component Using Properties ”; Previous Next As we have already learned in this tutorial before, React is a very flexible library with bendable rules, sometimes, but it strictly follows on one rule: if a component is defined as a function or class, it must act like a pure function with respect to their properties. A pure function in React is defined as a function whose input must not be changed so it does not alter its result. In short, the Props passed to a component are Read-Only. But as the application UIs are dynamic and change their inputs over time, we use “state” concept to handle it. The concept of state allows React components to change their result as a response to changing user actions, network responses, etc. without violating this rule. How to create a component using properties? In this chapter, let us see the steps to create a component using properties − We will first modify our ExpenseEntryItem component and try to use properties. Step 1 − Open our expense-manager application in your favorite editor. Open ExpenseEntryItem file in the src/components folder. Step 2 − Introduce construction function with argument props. constructor(props) { super(props); } Next, change the render method and populate the value from props. render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend date:</b> <em>{this.props.spenddate.tostring()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } Here, name represents the item”s name of type String amount represents the item”s amount of type number spendDate represents the item”s Spend Date of type date category represents the item”s category of type String Now, we have successfully updated the component using properties. import React from ”react” import ”./ExpenseEntryItem.css”; import styles from ”./ExpenseEntryItem.module.css” class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } } export default ExpenseEntryItem; index.js Now, we can use the component by passing all the properties through attributes in the index.js. import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItem from ”./components/ExpenseEntryItem” const name = “Grape Juice” const amount = 30.00 const spendDate = new Date(“2020-10-10”) const category = “Food” ReactDOM.render( <React.StrictMode> <ExpenseEntryItem name={name} amount={amount} spendDate={spendDate} category={category} /> </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 complete code to do it using CDN in a webpage is as follows − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>React based application</title> </head> <body> <div id=”react-app”></div> <script src=”https://unpkg.com/react@17/umd/react.development.js” crossorigin></script> <script src=”https://unpkg.com/react-dom@17/umd/react-dom.development.js” crossorigin></script> <script src=”https://unpkg.com/@babel/standalone/babel.min.js”></script> <script type=”text/babel”> class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } } const name = “Grape Juice” const amount = 30.00 const spendDate = new Date(“2020-10-10”) const category = “Food” ReactDOM.render( <ExpenseEntryItem name={name} amount={amount} spendDate={spendDate} category={category} />, document.getElementById(”react-app”) ); </script> </body> </html> Objects as properties Let us learn how to use JavaScript object as attributes in this chapter. Step 1 − Open our expense-manager application in your favorite editor. Open ExpenseEntryItem.js file. Step 2 − Next, change the render() method and access the input object item through this.props.item property. render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em>{this.props.item.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.item.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.item.category}</em></div> </div> ); } Open index.js and represent the expense entry item in JavaScript object. const item = { id: 1, name : “Grape Juice”, amount : 30.5, spendDate: new Date(“2020-10-10”), category: “Food” } Pass the object to the component using curly brace ({}) syntax in the component attributes. <ExpenseEntryItem item={item} /> index.js The complete code of index.js is as follows − import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItem from ”./components/ExpenseEntryItem” const item = { id: 1, name : “Grape Juice”, amount : 30.5, spendDate: new Date(“2020-10-10”), category: “Food” } ReactDOM.render( <React.StrictMode> <ExpenseEntryItem item={item} /> </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 complete code to do it using CDN in a webpage is as follows − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>React based application</title> </head> <body> <div id=”react-app”></div> <script src=”https://unpkg.com/react@17/umd/react.development.js” crossorigin></script> <script src=”https://unpkg.com/react-dom@17/umd/react-dom.development.js” crossorigin></script> <script src=”https://unpkg.com/@babel/standalone/babel.min.js”></script> <script type=”text/babel”> class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em>{this.props.item.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.item.spendDate.toString()}</em> </div> <div><b>Category:</b> <em>{this.props.item.category}</em> </div> </div> ); } } const item = { id: 1, name : “Grape Juice”, amount : 30.5, spendDate: new Date(“2020-10-10”), category: “Food” } ReactDOM.render( <ExpenseEntryItem item={item} />, document.getElementById(”react-app”) ); </script> </body> </html> Print Page Previous Next Advertisements ”;

ReactJS – Event management

ReactJS – Event Management ”; Previous Next 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. Events in React are divided into three categories: Mouse Events − onClick, onDrag, onDoubleClick Keyboard Events − onKeyDown, onKeyPress, onKeyUp Focus Events − onFocus, onBlur 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. This entire process of working with events using Event Handlers is known as Event Management. Event Management in ReactJS Event management is one of the important features in a web application. It enables the user to interact with the application. React supports all events available in a web application. React event handling is very similar to DOM events with little changes. Following are some of the common events one can observe in React-based websites − Clicking on a component. Scrolling the current page. Hovering over elements of the current page. Submitting a form. Redirecting to another webpage. Loading images. Synthetic React Events In JavaScript, when an event is specified, you will be dealing with a react event type called a synthetic event instead of regular DOM events. SyntheticEvent is a simple cross-browser wrapper for native event instances making the events work identically across all browsers. All event handlers must be passed as instances of this wrapper. However, it is expensive in terms of CPU resources as every synthetic event created needs to be garbage-collected. Every synthetic event object has the following attributes: boolean bubbles boolean cancelable DOMEventTarget currentTarget boolean defaultPrevented number eventPhase boolean isTrusted DOMEvent nativeEvent void preventDefault() boolean isDefaultPrevented() void stopPropagation() boolean isPropagationStopped() void persist() DOMEventTarget target number timeStamp string type Since synthetic events use a lot of resources, they are usually reused and all its properties will be nullified after invoking the event callback to optimize their performance in the browser. SyntheticEvent has the same interface as the native event. And as the synthetic events are authorized by the document node, native events are triggered first followed by the synthetic events. Adding an Event As we have already seen, React has the same events as HTML: click, change, mouseover etc. However, the React events are defined with a camelCase and the reaction is written inside the curly braces instead. The syntax of adding an event differs in a functional component and class component. Following is the syntax to add an onClick event in a functional component of React: onClick = {action to be performed} Following is the syntax to add an onClick event in a class component of React: onClick = {this.action_to_be_performed} Handling an Event Let us now learn how to handle these events in a React application with the help of the following step-by-step process. Define an event handler method to handle the given event. log() { console.log(“Event is fired”); } React provides an alternative syntax using lambda function to define event handler. The lambda syntax is − log = () => { console.log(“Event is fired”); } Passing Arguments to Event Handler There are two methods available to pass arguments to an Event Handler: Arrow Method Bind Method Arrow Method If you want to know the target of the event, then add an argument e in the handler method. React will send the event target details to the handler method. log(e) { console.log(“Event is fired”); console.log(e.target); } The alternative lambda syntax is − log = (e) => { console.log(“Event is fired”); console.log(e.target); } If you want to send extra details during an event, then add the extra details as initial argument and then add argument (e) for event target. log(extra, e) { console.log(“Event is fired”); console.log(e.target); console.log(extra); console.log(this); } The alternative lambda syntax is as follows − log = (extra, e) => { console.log(“Event is fired”); console.log(e.target); console.log(extra); console.log(this); } Bind Method We can also bind the event handler method in the constructor of the component. This will ensure the availability of this in the event handler method. constructor(props) { super(props); this.logContent = this.logContent.bind(this); } If the event handler is defined in alternate lambda syntax, then the binding is not needed. this keyword will be automatically bound to the event handler method. Set the event handler method for the specific event as specified below − <div onClick={this.log}> … </div> To set extra arguments, bind the event handler method and then pass the extra information as second argument. <div onClick={this.log.bind(this, extra)}> … </div> The alternate lambda syntax is as follows − <div onClick={this.log(extra, e)}> … </div> Here, Create a event-aware component Introduce events in Expense manager app Print Page Previous Next Advertisements ”;