ReactJS – Date Picker

ReactJS – Date Picker ”; Previous Next React provides form 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 to the React library and it has best support for date picker component as well. Let us learn how to use date picker component from react-bootstrap library in this chapter. What is date picker? Date picker allows the developer to easily choose a date instead of entering it through text box with correct formatting details. HTML input element has type attributes to refer the type of data to be entered into the element. One of the type is date. Setting the type in a input element will enable the date picker. <input type=”date”> React bootstrap provides Form.Control component to create various input elements. Developer can use it to create date picker control. Some of the useful props of the Form.Control are as follows − ref (ReactRef) − Ref element to access underlying DOM node as (elementType) − Enable to specify element other than *<input>* disabled (boolean) − Enable / Disable the control element htmlSize (number) − Size of the underlying control element id (string) − Id of the control element. Uses *controlId* of the parent *Form.Group* component, if not specified here. IsInValid (boolean) − Enables / Disable the style associated with invalid data IsValid (boolean) − Enables / Disable the style associated with valid data plaintext (boolean) − Enable / disable the input and render it as plain text. To be used along with *readonly* props readOnly (boolean) − Enable / disable the readonly attribute of the control size (sm | lg) − Size of the input element type (string) − Type of the input element to be rendered value (string | arrayOf | number) − Value of the underlying control. Manipulated by *onChange* event and the initial value will be default to *defaultValue* props bsPrefix (string) − Prefix used to customize the underlying CSS classes onChange (boolean) − Callback function to be called when *onChange* event is fired A simple date control component can be used as shown below − <Form.Group className=”mb-3″ controlId=”password”> <Form.Label>Date of birth</Form.Label> <Form.Control type=”date” /> </Form.Group> Applying Date picker 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 css classes Next, create a simple date component, SimpleDatePicker (src/Components/SimpleDatePicker.js) and render a form as shown below − import { Form, Button } from ”react-bootstrap”; function SimpleDatePicker() { return ( <Form> <Form.Group className=”mb-3″ controlId=”name”> <Form.Label>Name</Form.Label> <Form.Control type=”name” placeholder=”Enter your name” /> </Form.Group> <Form.Group className=”mb-3″ controlId=”password”> <Form.Label>Date of birth</Form.Label> <Form.Control type=”date” /> </Form.Group> <Button variant=”primary” type=”submit”> Submit </Button> </Form> ); } export default SimpleDatePicker; Here we have, Used Form.Control with type date to create date picker control. Used Form component to create a basic form component. Used Form.Group to group form control and label. Next, open App component (src/App.js), import the bootstrap css and render the date picker as shown below − import ”./App.css” import “bootstrap/dist/css/bootstrap.min.css”; import SimpleDatePicker from ”./Components/SimpleDatePicker” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleDatePicker /> </div> </div> </div> ); } export default App; Here, Imported the bootstrap classes using import statement Rendered our new SimpleDatePicker component. Included the App.css style Finally, open the application in the browser and check the final result. Date picker will be rendered as shown below − Summary React Bootstrap date picker component provides necessary options to create date picker form control. Print Page Previous Next Advertisements ”;

ReactJS – Form Components

ReactJS – Form Components ”; Previous Next React provides form 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 to the React library and it has best support for form component as well. Let us learn how to use Form component from react-bootstrap library in this chapter. What is Form component? Form programming is one of the highlight feature of a web application. It is used to collect information from user in the front-end and then pass it to the server side for further processing. The collected information will be validated in the front-end before sending it to the server. HTML has different input tags like text, checkbox, radio, etc., to collect different type of information from user. React bootstrap provides nearly all bootstrap based form components. They are as follows − Form Form component is used to render the basic html form (form). It is the top most form component. Some of the useful props of the Form component is as follows − ref (ReactRef) − Ref element to access underlying DOM node. as (elementType) − Enable to specify element other than *<form>*. validated (boolean) − To specify that the form is being validated. Toggling the value to true will show the validation styles set in the form. A simple form component can be used as shown below − <Form> <!– Use form control–> </Form> Form.Control Form.Control component is used to render various input element through it”s type props. Some of the useful props of the Form.Control component is as follows − ref (ReactRef) − Ref element to access underlying DOM node. as (elementType) − Enable to specify element other than *<input>*. disabled (boolean) − Enable / Disable the control element. htmlSize (number) − Size of the underlying control element. id (string) − Id of the control element. Uses *controlId* of the parent *Form.Group* component, if not specified here. IsInValid (boolean) − Enables / Disable the style associated with invalid data. IsValid (boolean) − Enables / Disable the style associated with valid data. plaintext (boolean) − Enable / disable the input and render it as plain text. To be used along with *readonly* props. readOnly (boolean) − Enable / disable the readonly attribute of the control. size (sm | lg) − Size of the input element. type (string) − Type of the input element to be rendered. value (string | arrayOf | number) − Value of the underlying control. Manipulated by *onChange* event and the initial value will be default to *defaultValue* props bsPrefix (string) − Prefix used to customize the underlying CSS classes. onChange (boolean) − Callback function to be called when *onChange* event is fired. A simple form control component can be used as shown below − <> <Form.Control type=”text” size=”lg” placeholder=”Large text” /> <br /> <Form.Control type=”text” placeholder=”Normal text” /> <br /> <Form.Control type=”text” size=”sm” placeholder=”Small text” /> </> Form.Label Form.Label component is used to render the html label component (). Some of the useful props of the Form.Label component is as follows − ref (ReactRef) − Ref element to access underlying DOM node. as (elementType) − Enable to specify element other than *<label>*. htmlFor (string) − Used to specify the input element for which the particular label is created. If the *htmlFor* is not specified, then it will use *controlId* of the top level *Form.Group* component. column (boolean | sm | lg) − To render the label using *<Col>* component for layout purpose. visuallyHidden (boolean) − To visually hide the label and yet allowed to used by assistive technology. bsPrefix (string) − Prefix used to customize the underlying CSS classes. Form.Group Form.Group component is used to group a form control and label. It will be used to layout the control with respect to its label. Some of the useful props of the Form.Group component is as follows − ref (ReactRef) − Ref element to access underlying DOM node. as (elementType) − Enable to specify element other than *<form>*. controlId (string) − Id to refer the group of control and label. It will be used as id for form control inside the group, if the control does not have *Id* props. A simple form group along with form label can be used as shown below − <Form.Group controlId=”formFile” className=”mb-3″> <Form.Label>Upload file</Form.Label> <Form.Control type=”file” /> </Form.Group> Form.Text Form.Text component is used to show helpful message for the form controls(*). Some of the useful props of the Form* component is as follows − ref (ReactRef) − Ref element to access underlying DOM node. as (elementType) − Enable to specify element other than *<form>*. muted (boolean) − Apply *text-muted* class. bsPrefix (string) − Prefix used to customize the underlying CSS classes. A simple form text component can be use as follows − <Form.Label htmlFor=”pwd”>Password</Form.Label> <Form.Control type=”password” id=”pwd” aria-describedby=”passwordHelpMessage” /> <Form.Text id=”passwordHelpMessage” muted> Please set password within 8 – 12 characters long. Use minimum of 1 digit, 1 special character and 1 capital letter. Try to use strong password. </Form.Text> Form.Select Form.Select component is used to render the select element(select). Some of the useful props of the Form.Select component is as follows − disabled (boolean) − Enable / Disable the control element. htmlSize (number) − Size of the underlying control element./p> IsInValid (boolean) − Enables / Disable the style

ReactJS – PropTypes

ReactJS – PropTypes ”; Previous Next JavaScript is a dynamically typed language. It means that JavaScript does not need the type of a variable to be declared or specified. During program execution (Runtime), JavaScript checks the value assigned to variable and then it infers the type of the variable. For example, if a variable, num is assigned to John, then it infers that the type of num is string. If the same variable, num is assigned to 10, then it infers that the type of num is number. var num = ”John” // The type of `num` is string var num = 10 // The type of `num` is number Dynamic typing is good for scripting language as it speeds up the development. The flip side of the dynamic typing is that the JavaScript engine does not know the type of a variable before it start executing the program. This prevent the JavaScript engine to find or identify certain bugs. For example, the below mentioned code does not execute and stops the program. var num = 10 var name = ”John” var result = num + name // throws error during runtime React and types In React, each component will have multiple props and each props should be assigned to value with correct type. Component props with wrong type will throw unexpected behavior. To better understand the problem, let us create a new application and create a component, which sums its properties and shows the result. To create a new React app, execute below command, create-react-app myapp Once the application is created, create a new component, Sum under component folder (src/components/PropTypes/Sum.js) import React from ”react” 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> } } export default Sum Here, Sum component accept two number, num1 and num2 and prints the summation the given two number. The component will work if it is provided the number value for the props. But, if sum component is supplied with string then it will show NaN as the sum of the two properties. Their is no way to find that the given value for num1 and num2 props are not in correct format. Let us use Sum component in the our root component (src/App.js) and see how it renders. import Sum from “./components/PropTypes/Sum”; function App() { var num1 = 10 var num2 = 200 var name1 = “John” var name2 = “Peter” return ( <div> <Sum num1={num1} num2={num2} /> <Sum num1={name1} num2={name2} /> </div> ); } export default App; 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 sample application and see how it helps to catch properties type mismatch issue. Install prop-types package using node package manager (npm) as shown below − npm i prop-types –save Now, specify the type of the properties of Sum component 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 Finally, run the application using below command − npm start 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 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 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) { … }) Print Page Previous Next Advertisements ”;

ReactJS – Fragments

ReactJS – Fragments ”; Previous Next Fragment is the simple solution to group multiple react elements without adding extra markup in the DOM. In React, render method of a component is allowed to return a react element. For a component to return multiple elements, the elements needs to be wrapped into a generic container element. For example, to return multiple p elements, it should be wrapped around a div element as shown below − <div> <p>One</p> <p>Two </p> </div> Wrapping a generic root element is fine for most of the scenarios, but certain scenario needs special handling. They are as follows − Certain elements such as li, td, etc., may not be wrapped around generic element. When the component needs to return only a partial list of elements (which will be eventually wrapped in the parent component). Let us write a simple component to better understand our problem. The functionality of the component is to return a partial list of customers as shown below − <li>John</li> <li>Peter</li> Create a new application using create-react-app and start the application. create-react-app myapp cd myapp npm start Create a component, ListOfCustomer under components folder (src/components/ListOfCustomer.js) import React from ”react” class ListOfCustomer extends React.Component { constructor(props) { super(props); } render() { console.log(this.props) var names = this.props[”names”]; var namesList = names.map( (name, index) => <li>{name}</li> ) return <ul>{namesList}</ul> } } export default ListOfCustomer Here, the component loop over the names property and render it into a list of li elements. Now, use the component in our root component (App.js) import ListOfCustomer from ”./components/ListOfCustomer”; function App() { var names = [“John”, “Peter”] return ( <ul> <ListOfCustomer names={names} /> </ul> ); } export default App; This will result in rendering of multiple ul as shown below − <ul><ul><li>John</li><li>Peter</li></ul></ul> Let us change the component to use React.Fragment import React, { Fragment } from ”react” class ListOfCustomer extends React.Component { constructor(props) { super(props); } render() { console.log(this.props) var names = this.props[”names”]; var namesList = names.map( (name, index) => <li>{name}</li> ) return <React.Fragment>{namesList}</React.Fragment> } } export default ListOfCustomer Now, our component renders valid HTML document. <ul><li>John</li><li>Peter</li></ul> Keyed Fragments In the above example, React throws a warning in the developer console as shown below − Warning: Each child in a list should have a unique “key” prop. Check the render method of `ListOfCustomer`. See https://reactjs.org/link/warning-keys for more information. li ListOfCustomer@http://localhost:3000/main.4bbe8fa95c723e648ff5.hot-update.js:26:10 ul App render – ListOfCustomer.js:9 As the warning says, React excepts unique key for each element in the list. It uses the key to identify which elements are changed. are added or are removed. React.Fragment allows a key to be passed through its key attribute. React will use it internally to render only the modified item in the list. Let us change our code and add key to React.Fragment as shown below − import React, { Fragment } from ”react” class ListOfCustomer extends React.Component { constructor(props) { super(props); } render() { console.log(this.props) var names = this.props[”names”]; var namesList = names.map( (name, index) => <li key={index}>{name}</li> ) return <React.Fragment>{namesList}</React.Fragment> } } export default ListOfCustomer This will remove the error. Short syntax React.Fragment has an alternative shorter syntax, which is both easy to use and readable. <> JSX element </> Let us change our code to accommodate the shorter syntax. The updated code is as follows − import React, { Fragment } from ”react” class ListOfCustomer extends React.Component { constructor(props) { super(props); } render() { console.log(this.props) var names = this.props[”names”]; var namesList = names.map( (name, index) => <li key={index}>{name}</li> ) return <>{namesList}</> } } export default ListOfCustomer Print Page Previous Next Advertisements ”;

ReactJS – Error Boundaries

ReactJS – Error Boundaries ”; Previous Next In general, it is quite challenging to catch error and process it without affecting the UI of the application. React introduces a concept called error boundaries to catch a error during UI rendering, process it in the background and show a fallback UI in the front-end application. This will not affect the UI application as it is handled using alternative UI like warning message instead of broken pages. Let us learn what is error boundary and how to apply it in our application in this chapter. Concept of error boundary Error boundaries are normal react component with special features to catch all the errors occurred anywhere in the component tree. The error caught during the process can be logged and then alternative user interface specifying the error can be shown to the user. A normal react class based component can be upgraded to a component supporting error boundary by implementing two functions. static getDerivedStateFromError() − This is a static function and will be called when an error occurs in the application. static getDerivedStateFromError(error) { return { hasError: true }; } Here, hasError is a custom state variable specifying that the application has some error and can be used in subsequent render to show fallback UI instead of normal UI. componentDidCatch() − This is a component life cycle event called with the error information when an error occurs in the component tree componentDidCatch(error, errorInfo) { // log the error in console or store it somewhere using a log service } Once a component is upgraded to handle the error, then it can be use anywhere in the application as normal component. Let us consider the name of the component is SimpleErrorBoundary, then it can be use as shown below − <SimpleErrorBoundary> <MyComponent /> </SimpleErrorBoundary> Here, React will catch the error occurs anywhere in the MyComponent component and send it to SimpleErrorBoundary component for further processing. React will not catch all error except error occurring in below scenarios, Event handlers − Event handlers are plain javascript function, which can use try/catch and render fallback UI itself and may not need error boundary hint. Async code like setTimeout. Server side rendering. Error boundary is exclusively for front-end application. Error happening in the error boundary component itself. Applying error boundary Let us create a new react application to learn how to apply error boundary 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. Then, create a simple component, SimpleErrorBoundary (src/Components/SimpleErrorBoundary.js) and render either fallback UI during error or children components as shown below − import React from “react”; class SimpleErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log(error); console.log(errorInfo); } render() { if (this.state.hasError) { return <h1>Please contact the administrator.</h1>; } return this.props.children; } } export default SimpleErrorBoundary; Here, hasError is a state variable initialized with false value. getDerivedStateFromError updates the error state when there is an error componentDidCatch logs the error into the console. render will render either error UI or children based on the error in the application. Next, create a simple component, Hello (src/Components/Hello.js) and render a simple text message as shown below − import React from “react”; class Hello extends React.Component { constructor(props) { super(props) } render() { if(this.props.name == “error”) { throw(”Invoked error”) } return ( <div>Hello, {this.props.name}</div> ); } } export default Hello; Here we have, Used name props to show the greeting message. Throws error if the given name is error. Next, open App component (src/App.js), and use SimpleErrorBoundary component as shown below − import ”./App.css” import React from ”react”; import SimpleErrorBoundary from ”./Components/SimpleErrorBoundary” import Hello from ”./Components/Hello” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleErrorBoundary> <Hello name=”error” /> </SimpleErrorBoundary> </div> </div> </div> ); } export default App; Here we have, Imported SimpleErrorBoundary component from the react package. Used SimpleErrorBoundary component with error as value for name props. Finally, open the application in the browser and check the final result. Open the console in the dev tools and you can see the error information as shown below − Invoked error SimpleErrorBoundary.js:17 { componentStack: ”n at Hello (http://localhost:3000/static/js/bun…09:5)n at divn at divn at divn at App” } Summary Error boundary is safe and valuable component to handle unexpected error in the front end application. Without error boundary, it will be hard to hide the error and get the valuable debugging information about the error happened. Print Page Previous Next Advertisements ”;

ReactJS – Reconciliation

ReactJS – Reconciliation ”; Previous Next Reconciliation is an internal process of React library. As we know, react application will create a virtual DOM and then updates the actual DOM of the application based on the virtual DOM. Whenever react receives an update request, it will first create a virtual DOM and then compare the virtual DOM with previous state using different diffing algorithm and then only if it is absolutely necessary, it will update the DOM. Even though the diff algorithm and updating the DOM is internal to React core, understanding the some of the internal will help us to tweak our application to take maximum leverage of the React library. Diffing Algorithm Let us see some of the diffing algorithm applied by react core in this chapter. Element of same type Whenever a react component changes an element from one type to another type (say from div to more specific p), the whole of the react virtual dom tree will get changed and it triggers the DOM updates. <!– Before –> <div> <Content /> </div> <!– After –> <p> <Content /> </p> Here, the entire element will get updated. DOM Attributes of the same type. When the element are of same type, react will check for attributes for differences. If react finds any new changes in attribute and its values, then it will only update the changed attributes. <!– Before –> <div className=”someClass”> <Content /> </div> <!– After –> <div className=”someOtherClass”> <Content /> </div> Here, only the class attribute of the DOM instance will get updated. DOM Attributes (style) of the same type. When the elements are of same type and react find differences in style properties, then it will update only the properties of the style. <!– Before –> <div style={{fontFamily: ”Arial”}} /> <p> … </p> </div> <!– After –> <div style={{color: ”red”, fontFamily: ”Arial”}} /> <p> … </p> </div> Here, only the color properties of the div element”s style will be updated Components elements of same type − Whenever react sees same react component type, then it will call componentWillUpdate event and other update events of the react component for the component to update its state. Then, it will call the render method of the component and the algorithm recurses Collection of child elements of same type − Whenever react sees a collections of children of same type, it will check the element in order for differences. So, if we have a new first child, then the whole collection will get updated. <!– Before –> <ul> <li>Peter</li> <li>Olivia</li> </ul> <!– After –> <ul> <li>John</li> <li>Peter</li> <li>Olivia</li> </ul> Here, whole elements (children of ul element) will get updated as the first element (li) is an updated one. To solve the issue, we can introduce a key attribute as shown in the below code snippet. React has a special key attribute for this purpose. <!– Before –> <ul> <li key=”1″>Peter</li> <li key=”2″>Olivia</li> </ul> <!– After –> <ul> <li key=”3″>John</li> <li key=”1″>Peter</li> <li key=”2″>Olivia</li> </ul> Summary React tries to optimize the diffing algorithm in every release to make sure that the updates are minimum. Minimum updates means better performance of the application. Knowing the internal and coding accordingly by following best practices, we can improve our application performance exponentially. Print Page Previous Next Advertisements ”;

ReactJS – Forwarding Refs

ReactJS – Forwarding Refs ”; Previous Next Ref is an escape hatch to manipulate the DOM directly without the effect of state changes updating the component. Ref can be applied to DOM element but to apply the Ref to a React component and get the DOM element deep inside the component, Forwarding Ref is the choice. Forwarding Ref lets a component to receive a ref from the top level component and pass it further down into the next level component for the purpose of getting the DOM element. Let us learn how to use Forwarding ref in this chapter. Signature of the forwardRef method The signature of forwardRef is as follows − const new-component = React.forwardRef(fn) Where the signature of the fn is as follows − (props, ref) => { // renders a react component by attaching the ref and returns it } A simple example of using forwardRef is as follows − const MyInput = React.forwardRef((props, ref) => ( <input type=”text” ref={ref} value={props.value} /> )); const myRef = React.createRef(); <MyInput ref={myRef} value=”Hi” /> Here, MyInput gets the ref from the top level and pass it to the underlying input element. myRef is is assigned to MyInput component. MyInput component passes myRef to underlying input element. Finally, myRef points to the input element. Applying forwardRef in a component Let us learn the concept of forwardRef by developing an application. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, open App.css (src/App.css) and remove all the CSS classes. Then, create a simple component, SimpleForwardRef (src/Components/SimpleForwardRef.js) as shown below − import React from “react”; const SimpleForwardRef = React.forwardRef((props, ref) => ( <input type=”text” ref={ref} value={props.value} /> )); export default SimpleForwardRef Here we have, Used forwardRef to pass the ref to input element. input element used ref props to set the ref value. Next, open App component (src/App.js) and update the content with SimpleForwardRef component as shown below − import ”./App.css” import React, { useEffect } from ”react”; import SimpleForwardRef from ”./Components/SimpleForwardRef” function App() { const myRef = React.createRef(); useEffect(() => { setTimeout(() => { myRef.current.value = “Hello” }, 5000) }) return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleForwardRef ref={myRef} value=”Hi” /> </div> </div> </div> ); } export default App; Here, myRef is created using createRef method and passed it into SimpleForwardRef component. myRef represent the input element rendered by SimpleForwardRef component. useEffect will access the input element through myRef and try to change the value of input from hi to Hello. Finally, open the application in the browser. The value of the input will be get changed to Hello after 5 seconds as shown below − Summary Forward ref enhances the ref concept to be used anywhere in the react application. Any DOM element, which may be any level deep inside the component hierarchy can be accessed and manipulated using forwarding ref concept. Print Page Previous Next Advertisements ”;

ReactJS – Using useCallback

ReactJS – useCallback ”; Previous Next The useCallback hook is similar to useMemo hook and provides the functionality of memoizing the function instead of values. Since callback function in an integral part of the JavaScript programming and callback functions are passed by references, react provides a separate hook, useCallback to memoize the callback functions. In theory, useCallback functionality can be done using useMemo hook itself. But, useCallback improves the readability of the react code. Signature of the useCallback hook The signature of the useCallback hook is as follows − const <memoized_callback_fn> = useCallback(<callback_fn>, <dependency_array>); Here, the useCallback accepts two input and returns a memoized callback function. The input parameter are as follows − callback_fn − Callback function to be memorized. dependency_array − Hold variables, upon which the callback function depends. The output of the useCallback hook is the memoized callback function of the callback_fn. Usage of useCallback hook is as follows − const memoizedCallbackFn = useCallback(() => { // code }, [a, b]) Note − The useCallback(callback_fn, dependency_array) is equivalent to useMemo(() => callback_fn, dependency_array). Applying useCallback Let us learn how to apply the useCallback hook by creating a react application. First of all, create and start a react application by using create-react-app command as shown below − create-react-app myapp cd myapp npm start Next, create a component, PureListComponent under components folder (src/components/PureListComponent.js) import React from “react”; function PureListComponent() { return <div>List</div> } export default PureListComponent Next, update the root component with PureListComponent component as shown below − import PureListComponent from ”./components/PureListComponent”; function App() { return ( <div style={{ padding: “5px” }}> <PureListComponent /> </div> ); } export default App; Next, open PureListComponent.js and add two props list of items to show in the component callback function to show the item clicked by user in the console import React from “react”; function PureListComponent(props) { const items = props[”items”]; const handleClick = props[”handleClick”] console.log(“I am inside the PureListComponent”) return ( <div> {items.map((item, idx) => <span key={idx} onClick={handleClick}>{item} </span> )} </div> ) } export default React.memo(PureListComponent) Here we have, Used items props to get the list of items Used handleClick to get the handler for click event Wrapped the component using React.memo to memoize the component. Since the component will render same output for the given set of input, it is called PureComponent in react. Next, let us update App.js and use the PureListComponent as shown below − import React, {useState, useEffect} from ”react”; import PureListComponent from ”./components/PureListComponent”; function App() { // array of numbers var listOfNumbers = […Array(100).keys()]; // callback function const handleCallbackFn = (e) => { console.log(e.target.innerText) } const [currentTime, setCurrentTime] = useState(new Date()) useEffect(() => { let interval = setInterval(() => { setCurrentTime(new Date()) }, 1000) return () => clearInterval(interval) }, [currentTime]) return ( <div style={ { padding: “5px” } }> <PureListComponent items={listOfNumbers} handleClick={handleCallbackFn}/> <div>Time: <b>{currentTime.toLocaleString().split(”,”)[1]}</b></div> </div> ); } export default App; Here we have Included a state, currentTime and updated it every second using setInterval to make sure the component rerenders every second. We may thought that PureListComponent will not rerender every second as it uses React.memo. But, it will rerender as the props value are of reference type. Next, update the root component and use useMemo and useCallback to preserve the array and callback function as shown below − import React, {useState, useEffect, useCallback, useMemo} from ”react”; import PureListComponent from ”./components/PureListComponent”; function App() { // array of numbers const listOfNumbers = useMemo(() => […Array(100).keys()], []); // callback function const handleCallbackFn = useCallback((e) => console.log(e.target.innerText), []) const [currentTime, setCurrentTime] = useState(new Date()) useEffect(() => { let interval = setInterval(() => { setCurrentTime(new Date()) }, 1000) return () => clearInterval(interval) }, [currentTime]) return ( <div style={ { padding: “5px” } }> <PureListComponent items={listOfNumbers} handleClick={handleCallbackFn}/> <div>Time: <b>{currentTime.toLocaleString().split(”,”)[1]}</b></div> </div> ); } export default App; Here we have, Used useMemo to preserve the items array Used useCallback to preserve the handleClick callback functions Finally, check the application in the browser and it will not rerender PureListComponent every second. Use cases of useCallback Some of the use cases of the useCallback hook is as follows − Pure functional component with function props useEffect or other hooks having function as dependency Usage of function during debouncing / throttling or similar action Advantages Advantages of useCallback hook are as follows − Simple to use API Easy to understand Improves the performance of the application Disadvantages Technically, useCallback have no disadvantages. But, heavy usage of useCallback in a application will bring below disadvantages. Decrease the readability of the application Decrease the Understandability of the application Debugging the application is complex Developer should have deep understanding of JavaScript language to use it Summary useCallback is easy to use and improves performance. At the same time, useCallback should be used only when it is absolutely necessary. It should not be used in every scenario. The general rule is check the performance of the application. if it needs improvement, then we can check whether the usage of useCallback will help to improve the performance. If we get positive response, then we can use it. Otherwise, we can leave it to the react to improve and optimize the performance of the application. Print Page Previous Next Advertisements ”;

ReactJS – Discussion

Discuss ReactJS ”; Previous Next React is an open source, JavaScript library for developing user interface (UI) in web application. React is developed and released by Facebook. Facebook is continuously working on the React library and enhancing it by fixing bugs and introducing new features. This tutorial starts with the architecture of React, how-to guide to setup projects, creating components, JSX and then walks through advanced concepts like state management, form programming, routing and finally conclude with step by step working example. Print Page Previous Next Advertisements ”;

ReactJS – Using useContext

ReactJS – Using useContext ”; 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 React provides a special hook, useContext to access and update the context information in the function component. Let use learn context and its corresponding hook in this chapter. How context works? Before understanding useContext hook, let us revisit 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 we have, 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 Signature of useContext The signature of the useContext is as follows − let contextValue = useContext( <contextName> ) Here, contextName refers the name of the context to be accessed. contextValue refers the current value of the referred context. An example code to access the context using hooks is as follows − const theme = useContext(ThemContext) Context usage through hook Let us update our application and use the context hook instead of context consumer. First of all, convert the HelloWorld component into function component. import React from “react”; function HelloWorld() { return <div>Hello World</div> } export default HelloWorld Next, access the current value of the context through useContext hook import React, { useContext } from “react” import ThemeContext from ”../ThemeContext” function HelloWorld() { let theme = useContext(ThemeContext) return <div>Hello World</div> } export default HelloWorld Next, update the rendering function to use the theme information fetched through context. import React, { useContext } from “react” import ThemeContext from ”../ThemeContext” function HelloWorld() { let theme = useContext(ThemeContext) return ( <div style={{ color: theme.color, backgroundColor: theme.backgroundColor }}> Hello World </div> ) } export default HelloWorld Here we have, Used useContext to access the ThemeContext context information. Used ThemeContext information to set background color and color of the text. Finally, open the browser and check the output of the application. Updating context In some scenarios, updating the context information is necessary. For example, we may provide an option to change the theme information by user. When user changes the theme, then the context should get updated. Updating the context will rerender all the child component, which will change the theme of the application. React provides an option to update the context by using both useState and useContext hook. Let us update our application to support theme selection. First of all, update the root component, App.js and use useState hook to manage the theme information as shown below − import ”./App.css” import { useState } from ”react” import HelloWorld from ”./components/HelloWorld” import ThemeContext from ”./ThemeContext” function App() { let initialTheme = { color: ”white”, backgroundColor: ”green” } const [theme, setTheme] = useState(initialTheme) return ( <ThemeContext.Provider value={{ theme, setTheme }}> <HelloWorld /> </ThemeContext.Provider> ); } export default App; Here we have, Used useState hook to set the theme information in the state of the root