ReactJS – Properties (props) ”; Previous Next React enables developers to create dynamic and advanced component using properties. Every component can have attributes similar to HTML attributes and each attribute”s value can be accessed inside the component using properties (props). For example, Hello component with a name attribute can be accessed inside the component through this.props.name variable. <Hello name=”React” /> // value of name will be “Hello* const name = this.props.name React properties supports attribute”s value of different types. They are as follows, String Number Datetime Array List Objects Using Props When we need immutable data in our component, we can just add props to reactDOM.render() function in main.js and use it inside our component. App.jsx import React from ”react”; class App extends React.Component { render() { return ( <div> <h1>{this.props.headerProp}</h1> <h2>{this.props.contentProp}</h2> </div> ); } } export default App; main.js import React from ”react”; import ReactDOM from ”react-dom”; import App from ”./App.jsx”; ReactDOM.render(<App headerProp = “Header from props…” contentProp = “Content from props…”/>, document.getElementById(”app”)); export default App; This will produce the following result. Default Props You can also set default property values directly on the component constructor instead of adding it to the reactDom.render() element. App.jsx import React from ”react”; class App extends React.Component { render() { return ( <div> <h1>{this.props.headerProp}</h1> <h2>{this.props.contentProp}</h2> </div> ); } } App.defaultProps = { headerProp: “Header from props…”, contentProp:”Content from props…” } export default App; main.js import React from ”react”; import ReactDOM from ”react-dom”; import App from ”./App.jsx”; ReactDOM.render(<App/>, document.getElementById(”app”)); Output is the same as before. State vs Props The following example shows how to combine state and props in your app. We are setting the state in our parent component and passing it down the component tree using props. Inside the render function, we are setting headerProp and contentProp used in child components. App.jsx import React from ”react”; class App extends React.Component { constructor(props) { super(props); this.state = { header: “Header from props…”, content: “Content from props…” } } render() { return ( <div> <Header headerProp = {this.state.header}/> <Content contentProp = {this.state.content}/> </div> ); } } class Header extends React.Component { render() { return ( <div> <h1>{this.props.headerProp}</h1> </div> ); } } class Content extends React.Component { render() { return ( <div> <h2>{this.props.contentProp}</h2> </div> ); } } export default App; main.js import React from ”react”; import ReactDOM from ”react-dom”; import App from ”./App.jsx”; ReactDOM.render(<App/>, document.getElementById(”app”)); The result will again be the same as in the previous two examples, the only thing that is different is the source of our data, which is now originally coming from the state. When we want to update it, we just need to update the state, and all child components will be updated. More on this in the Events chapter. Let us learn the following concepts one by one in this chapter. Create a component using Properties Nested Components Use Component Component Collection Print Page Previous Next Advertisements ”;
Category: reactjs
ReactJS – Using useState
ReactJS – Using useState ”; Previous Next useState is a basic React hook, which allows a function component to maintain its own state and re-render itself based on the state changes. The signature of the useState is as follows − const [ <state>, <setState> ] = useState( <initialValue> ) where, initialValue − Initial value of the state. state can be specified in any type (number, string, array and object). state − Variable to represent the value of the state. setState − Function variable to represent the function to update the state returned by the useState. The signature of the setState function is as follows − setState( <valueToBeUpdated> ) Where, valueToBeUpdated is the value to be updated for the state. The sample usage to set and update the user”s name is as follows − // initialize the state const [name, setName] = useState(”John”) // update the state setName(”Peter) Features Notable features of useState are as follows − Function Parameter − It Accepts a function (returns initial state) instead of initial value and execute the function only once during initial rendering of the component. This will help to improve the performance, if the computation of initial value is expensive. const [val, setVal] = useState(() => { var initialValue = null // expensive calculation of initial value return initialValue }) Verifies the previous values − It checks the current and previous value of the state and only if they are different, React renders its children and fires the effects. This will improve performance of the rendering. // … setName(”John”) // update the state and rerender the component // … // … setName(”John”) // does not fire the rendering of the children because the value of the state have not changed. // … Batches multiple state updates − Multiple state updates are batched and processed by React internally. If multiple state update has to be done immediately, then the special function flushSync provided by React can be used, which will immediately flush all the state changes. flushSync(() => setName(”Peter”)) Applying state hook Let us create a login form component and maintain the values of the form using useState hook. First of all, create and start a React application using below commands, create-react-app myapp cd myapp npm start Next, create a react component, LoginForm under component folder (src/components/LoginForm.js) import { useState } from ”react”; export default function LoginForm() { // render code } Next, create two state variable, username and password using useState hook as shown below − import { useState } from ”react”; export default function LoginForm() { const [username, setUsername] = useState(””) const [password, setPassword] = useState(””) // render code } Next, create a function to validate the login data as shown below − import { useState } from ”react”; export default function LoginForm() { const [username, setUsername] = useState(””) const [password, setPassword] = useState(””) let isEmpty = (val) => { if(val == null || val == ””) { return true; } else { return false; } } let validate = (e) => { e.preventDefault() if(!isEmpty(username) && !isEmpty(password)) { alert(JSON.stringify({ username: username, password: password })) } else { alert(“Please enter username / password”) } } // render code } Here, isEmpty is a function to check whether the data is available or empty. Next, render a login form with two input fields and use state variables (username and password), state updated methods (setUsername and setPassword) and validate method to process the form. import { useState } from ”react”; export default function LoginForm() { return ( <div style={{ textAlign: “center”, padding: “5px” }}> <form name=”loginForm”> <label for=”username”>Username: </label> <input id=”username” name=”username” type=”text” value={username} onChange={(e) => setUsername(e.target.value)} /> <br /> <label for=”password”>Password: </label> <input id=”password” name=”password” type=”password” value={password} onChange={(e) => setPassword(e.target.value)} /> <br /> <button type=”submit” onClick={(e) => validate(e)}>Submit</button> </form> </div> ) } Here, onChange uses the state setting function returned by hooks. onClick uses the validate function to validate and show the user entered data. The complete code of the LoginForm component is as follows − import { useState } from ”react”; export default function LoginForm() { const [username, setUsername] = useState(””) const [password, setPassword] = useState(””) let isEmpty = (val) => { if(val == null || val == ””) { return true; } else { return false; } } let validate = (e) => { e.preventDefault() if(!isEmpty(username) && !isEmpty(password)) { alert(JSON.stringify({ username: username, password: password })) } else { alert(“Please enter username / password”) } } return ( <div style={{ textAlign: “center”, padding: “5px” }}> <form name=”loginForm”> <label for=”username”>Username: </label> <input id=”username” name=”username” type=”text” value={username} onChange={(e) => setUsername(e.target.value)} /> <br /> <label for=”password”>Password: </label> <input id=”password” name=”password” type=”password” value={password} onChange={(e) => setPassword(e.target.value)} /> <br /> <button type=”submit” onClick={(e) => validate(e)}>Submit</button> </form> </div> ) } Next, update the root application component, App.js as below, import ”./App.css”; import HelloWorld from ”./components/HelloWorld”; import LoginForm from ”./components/LoginForm”; function App() { return ( <LoginForm /> ); } export default App; Next, open the browser and check the application. Application will gather the user entered data using state variable and validate it using validate function. if user entered proper data, it will show the data as shown below − Otherwise, it will throw the error as shown below − Object as state In class based state management, setState method supports partial update of the state object. For example, let us consider login form data is maintained in state as an object. { username: ”John”, password: ”secret” } Updating the username using setState will only update the username in the state object and preserve the password field. this.setState({ username: ”Peter”
ReactJS – Using useEffect
ReactJS – Using useEffect ”; Previous Next React provides useEffect to do side-effects in a component. Some of the side effects are as follows − Fetching data from external source & updating the rendered content. Updating DOM elements after rendering. Subscriptions Using Timers Logging In class based components, these side effects are done using life cycle components. So, useEffect hook is an effect replacement for below mentioned life cycle events. componentDidMount − Fires after the rendering is done for the first time. componentDidUpdate − Fires after the rendering is updated due to prop or state changes. componentWillUnmount − Fires after the rendered content is unmounted during destruction of component. Let us learn how to use effect hook in this chapter. Signature of useEffect The signature of useEffect is as follows − useEffect( <update function>, <dependency> ) where, the signature of the update function is as follows − { // code return <clean up function> } Here, Update function − Update function is the function to be executed after each render phase. This corresponds to componentDidMount and componentDidUpdate events Dependency − Dependency is an array with all the variables on which the function is dependent. Specifying the dependency is very important to optimize the effect hook. In general, update function is called after each render. Sometimes it is not necessary to render update function on each render. Let us consider that we are fetching data from external source and updating it after the render phase as shown below − const [data, setDate] = useState({}) const [toggle, setToggle] = useState(false) const [id, setID] = useState(0) useEffect( () => { fetch(”/data/url/”, {id: id}).then( fetchedData => setData(fetchedData) ) }) // code Component will rerender whenever data and toggle variable are updated. But as you see, we don”t need that the defined effect to be run during each update of toggle state. To fix the issue, we can pass an empty dependency as shown below − const [data, setDate] = useState({}) const [toggle, setToggle] = useState(false) const [id, setID] = useState(0) useEffect( () => { fetch(”/data/url/”, { id: id }).then( fetchedData => setData(fetchedData) ) }, []) The above code will run the effect only once after the first render. Even though it will fix the issus, the effects has to be run on every change of id. To make it happen, we can include id as dependency for the effects as shown below − const [data, setDate] = useState({}) const [toggle, setToggle] = useState(false) const [id, setID] = useState(0) useEffect( () => { fetch(”/data/url/”, { id: id }).then( fetchedData => setData(fetchedData) ) }, [id]) This will ensure that the effects will rerun only after the modification of id Cleanup function − Cleanup function is used to cleanup work during the usage of subscription function and timer function as shown below − const [time, setTime] = useState(new Date()) useEffect(() => { let interval = setInterval(() => { setTime(new Date()) }, 1000) return () => clearInterval(interval) }, [time]) Let us create a complete application to understand the cleanup function in later section. Features of effect hook Some of the notable features of effect hook are as follows − React allows multiple effect hook to be used in a function component. This will help us to write a function for each side effects and set it up as separate effect. Each hook will be run in the order in which it is declared. Developer should make sure that the order of effects are declared correctly. Dependency feature can be used to improve the performance and correct working of the side effects. Cleanup function prevents memory leaks and unnecessary firing of events. Fetching data using effect Let us create an application that will fetch data from external source and render it using useEffect hook 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, create a react component, NameList under component folder (src/components/NameList.js) function NameList() { return <div>names</div> } export default NameList Here, the purpose of the NameList component is to showcase the popular list of common names Next, update the root component, App.js to use the newly created NameList component. import NameList from “./components/NameList”; function App() { return ( <div style={{ padding: “5px”}}> <NameList /> </div> ); } export default App; Next, create a json file, names.json (public/json/names.json) and store popular names in json format as shown below. [ { “id”: 1, “name”: “Liam” }, { “id”: 2, “name”: “Olivia” }, { “id”: 3, “name”: “Noah” }, { “id”: 4, “name”: “Emma” }, { “id”: 5, “name”: “Oliver” }, { “id”: 6, “name”: “Charlotte” }, { “id”: 7, “name”: “Elijah” }, { “id”: 8, “name”: “Amelia” }, { “id”: 9, “name”: “James” }, { “id”: 10, “name”: “Ava” }, { “id”: 11, “name”: “William” }, { “id”: 12, “name”: “Sophia” }, { “id”: 13, “name”: “Benjamin” }, { “id”: 14, “name”: “Isabella” }, { “id”: 15, “name”: “Lucas” }, { “id”: 16, “name”: “Mia” }, { “id”: 17, “name”: “Henry” }, { “id”: 18, “name”: “Evelyn” }, { “id”: 19, “name”: “Theodore” }, { “id”: 20, “name”: “Harper” } ] Next, create a new state variable, data to store popular names in NameList component as shown below − const [data, setData] = useState([]) Next, create a new state variable, isLoading to store loading status as shown below − const [isLoading, setLoading] = useState([]) Next, use fetch method to get popular names from json file and set it into data state variable inside useEffect hook useEffect(() => { setTimeout(()
ReactJS – Table
ReactJS – Table ”; Previous Next React provides table 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 Table component as well. Let us learn how to use Table component from react-bootstrap library in this chapter. Table component Table component allows the developer to create simple table with bootstrap UI design in a web application. Table component accepts table tags as shown below − thead tbody tfoot Table component accepts a small set of props to customize the table component and they are follows − bordered (boolean) − Adds border to all sides of the table and cell. borderless (boolean) −Removes border to all sides of the table and cell. hover (boolean) − Enables a hover state for each row in the table (tbody). responsive (boolean | string) − Enables vertical scrolling for small devices. sm | md | lg | xl option enables the responsive for relevant devices. For example, sm will be enabled only when the device resolution is very small. size (string) − Enables compact rendering of the table. Possible options are sm, md, etc., striped (boolean | string) − Enables the zebra stripping to all table rows. columns option adds zebra stripping to columns as well. variant (dark) Enables dark variant when dark value is used. bsPrefix (string) − Prefix used to customize the underlying CSS classes. Applying Table 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 and react-bootstrap library using below command, npm install –save bootstrap react-bootstrap Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a simple table component, SimpleTable (src/Components/SimpleTable.js) and render a table as shown below − import { Table } from ”react-bootstrap”; function SimpleTable() { return ( <Table striped bordered hover> <thead> <tr> <th>#</th> <th>Name</th> <th>Age</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John</td> <td>25</td> <td>[email protected]</td> </tr> <tr> <td>1</td> <td>Peter</td> <td>15</td> <td>[email protected]</td> </tr> <tr> <td>1</td> <td>Olivia</td> <td>23</td> <td>[email protected]</td> </tr> </tbody> </Table> ); } export default SimpleTable; Here we have, Used striped props to create zebra tables. Used bordered props to enable border around the table and cells. Used hover props to enable hover state. Next, open App component (src/App.js), import the bootstrap css and update the content with bootstrap button as shown below − import ”./App.css” import “bootstrap/dist/css/bootstrap.min.css”; import SimpleTable from ”./Components/SimpleTable” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleTable /> </div> </div> </div> ); } export default App; Here we have, Imported the bootstrap classes using import statement. Rendered our new SimpleTable component. Included the App.css style. Finally, open the application in the browser and check the final result. Table component will be rendered as shown below − Add dark variant and column strip Let us apply dark variant and column strip option in our table component and see how it updates the table design. First of all, open our carousel application and update the SimpleCarousel component as shown below − import { Table } from ”react-bootstrap”; function SimpleTable() { return ( <Table bordered hover striped=”columns” variant=”dark”> // … Here we have, Used striped props with columns to enable column based zebra stripping as well. Used variant props with dark option to enable dark variant of the table design. Next, open the application in the browser and check the final result. Table component will be rendered with column strip and dark variant as shown below − Summary Bootstrap table component provides all necessary options to design a table in a simple, intuitive and flexible manner. 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 ”; 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 – Introduction to Hooks ”; Previous Next Until React 16.8, function components are simply stateless component. To add state to a component, we need to convert the function component into class based component. Also, function component does not have option to manipulate lifecycle events of a component. To enable state and lifecycle events in the function component, React introduced a new concept called Hooks. Hooks are plain JavaScript functions having access to state and lifecycle events of the component in which it is used / applied. In general, hooks starts with use keyword. React comes with a few built-in hooks and allows the creation of custom hooks as well. Built-in hooks Let us know the list of hooks available in React and its basic usage. useState − Used to manipulate state of the component. useReducer − Advanced version of useState hooks with reducer concept. useEffect − Used to hook into lifecycle of the component. useLayoutEffect − Similar to useEffect, but gets triggered synchronously after all DOM mutation or just before the DOM is going to painted on the screen. useContext − Provides access to the context provider inside a component. useMemo − Used to return a memoized version of a variable / function, which only changes based on supplied predefined set of dependencies. This will reduce the number of recomputation of expensive calculation and improves the performance of the application. useCallback − returns a memoized version of a callback function, which only changes based on supplied predefined set of dependencies. useRef − Provides access to a raw DOM node based on React ref object. useImperativeHandle − Used to expose ref based value in the child component to parent component. useDeferredValue − Used to defer a value similar to debouncing or throttling to defer updates. useDebug − Used to display label for custom hooks in React DevTools. useTransition − Used to identify the pending state of the transition. useId − Used to create unique ID for an element in the application. Applying hooks Let us learn how to use a hook in a function component by creating an application. Create a React application using create-react-app and start the application using below command create-react-app myapp cd myapp npm start Next, let us create a new Function component HelloWorld (src/components/HelloWorld.js), which render an input element and renders a greeting message based on the data entered into the input element by the user. import { useState } from ”react”; export default function HelloWorld() { const [name, setName] = useState(“World”) return ( <div style={{ textAlign: “center”, padding: “5px” }}> <input id=”name” name=”name” value={name} onChange={(e) => setName(e.target.value)} /> <div>Hello {name}</div> </div> ) } Here, useState is a hook, which receives an initial value and returns a state and a function to update the state. it receives World as initial value and returns an array with two items, a) initial value of the state (name) and b) a function to update state (setName). The syntax used is array destruction syntax to get and set the array values into name and setName variables. input is a react input element with an onChange event attached to it. onchange event get the user”s updated values through event.target.value and set it into the current state using setName function. Whenever user updates the input, onchange event fires and update the state, which inturn fires the render function of the component. Next, let us apply our component in our application (App.js) as shown below − import ”./App.css”; import HelloWorld from ”./components/HelloWorld”; function App() { return ( <HelloWorld /> ); } export default App; Finally, open the browser and check the results by changing the input value. The message gets updated whenever the input changes as shown below − Advantages of Hooks Function component have many advantages over class based component when used along with Hooks. They are as follows − Hooks are easy to understand and quick to start coding. The complexity of the application can be kept minimum in a large application. In class based component, the complexity (state management and handling lifecycle events) grows as the project grows. this in class (component) is hard to understand for a beginner in JavaScript programming. Since Function component and hooks don”t depends on this, developers can quickly start coding in React without steep learning curve. Stateful logic can be reused easily between components. Function component can be used along with class based component, which makes it easily adoptable in the existing project of any size. Function component can be written is few lines of code compared to class based components. Disadvantages of Hooks Hooks are alternative methodology to create components and it has its own disadvantages as well. They are as follows − Hooks should be called only at top level and should be avoided inside a condition, loop or nested function. Hooks are specialized features that they may not be best fit for certain situation and we may have to restore to class based component. React handles the internals of hooks without exposing the core for optimization, which makes it less flexible and not suitable for certain scenarios. Summary Hooks are relatively new way of creating components. Large collection of project are still using class based component. Converting the component in those projects from class based to function based is not practically possible and we have to live with it. Instead, we can convert the application in the phased manner. Print Page Previous Next Advertisements ”;
ReactJS – Use Component ”; Previous Next A React component represents a small chunk of user interface in a webpage. The primary job of a React component is to render its user interface and update it whenever its internal state is changed. In addition to rendering the UI, it manages the events belongs to its user interface. To summarize, React component provides below functionalities. Using Components in ReactJS In this chapter, let us use newly created components and enhance our ExpenseEntryItem component. Step 1 − Open our expense-manager application in your favorite editor and open the ExpenseEntryItem.js file. Then, import FormattedMoney and FormattedDate using the following statements. import FormattedMoney from ”./FormattedMoney” import FormattedDate from ”./FormattedDate” Step 2 − Next, update the render method by including FormattedMoney and FormattedDater component. render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em> <FormattedMoney value={this.props.item.amount} /> </em> </div> <div><b>Spend Date:</b> <em> <FormattedDate value={this.props.item.spendDate} /> </em> </div> <div><b>Category:</b> <em>{this.props.item.category}</em></div> </div> ); } Here, we have passed the amount and spendDate through value attribute of the components. The final updated source code of the ExprenseEntryItem component is given below − import React from ”react” import FormattedMoney from ”./FormattedMoney” import FormattedDate from ”./FormattedDate” 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> <FormattedMoney value={this.props.item.amount} /> </em> </div> <div><b>Spend Date:</b> <em> <FormattedDate value={this.props.item.spendDate} /> </em> </div> <div><b>Category:</b> <em>{this.props.item.category}</em></div> </div> ); } } export default ExpenseEntryItem; index.js Open index.js and call the ExpenseEntryItem component by passing the item object. 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”) ); Next, serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. Print Page Previous Next Advertisements ”;
ReactJS – Code Splitting
ReactJS – Code-Splitting ”; Previous Next Bundling is one of the important stage in a front end application. It bundles all the front end code along with dependency into one large bundle (bundle.js). The final bundle is size optimized by the bundler. Some of the popular bundler are webpack, parcel and rollup. The final bundle will be fine in most cases. If the final bundled code is big, then the bundler can be instructed to bundle the code into multiple item instead of single, big chunk. Let us learn how to hint the bundler to split the code and bundle it separately. Dynamic import Dynamic import instruct the bundler to split the code. Dynamic import is basically fetching the required module based on the necessity. The code to do normal is as shown below − import { round } from ”./math”; console.log(round(67.78)); The same code can be imported dynamically as shown below − import(“./math”).then(math => { console.log(math.round(67.78); }); React Lazy component React provides a function, React.lazy to dynamically import a component. Normally, as we know, a react component will be imported as shown below − import MyComponent from ”./MyComponent”; To import the above component dynamically using React.lazy() function is as shown below − const MyComponent = React.lazy(() => import(”./MyComponent”)); The imported component should be wrapped into a Suspense component to use it in the application. import React, { Suspense } from ”react”; const MyComponent = React.lazy(() => import(”./MyComponent”)); function App() { return ( <div> <Suspense fallback={<div>Loading…</div>}> <MyComponent /> </Suspense> </div> ); } Suspense component is used to load a temporary UI during the loading of the original component. Suspense component includes a fallback props to specify the fallback UI. The fallback UI can be any React element. Sometimes, the dynamic component may fail to load due to network issue or code error. We can use error boundary to handle those situation as shown below − import React, { Suspense } from ”react”; import MyErrorBoundary from ”./MyErrorBoundary”; const MyComponent = React.lazy(() => import(”./MyComponent”)); const AnotherComponent = () => ( <div> <MyErrorBoundary> <Suspense fallback={<div>Loading…</div>}> <section> <MyComponent /> </section> </Suspense> </MyErrorBoundary> </div> ); Here, MyErrorBoundary is wrapped around the Suspense component. If there is any error in loading MyComponent, then MyErrorBoundary handles the error and fallback to the generic UI specified in its component. One of best scenario to apply the code splitting is routing. Routing can be used to apply the code splitting as shown below − import React, { Suspense, lazy } from ”react”; import { BrowserRouter, Routes, Route } from ”react-router-dom”; const Home = lazy(() => import(”./routes/Home”)); const About = lazy(() => import(”./routes/About”)); const App = () => ( <BrowserRouter> <Suspense fallback={<div>Loading…</div>}> <Routes> <Route path=”/” element={<Home />} /> <Route path=”/about” element={<About />} /> </Routes> </Suspense> </BrowserRouter> ); Here, All routes (component) are loaded using React.lazy() feature Since all routes (Home and About ) are loaded through dynamic import, each route will load only the necessary component instead of all components during its initialization. React.lazy() supports only default exports. In React, we can export a component by specifying a dynamic name instead of default keyword as shown below − export const MyComponent = /* … */; To make it usable in React.lazy(), we can reexport the component using default keyword as shown below − export { MyLazyComponent as default } from “./MyComponent.js”; Then, we can import it as usual, import React, { lazy } from ”react”; const MyComponent = lazy(() => import(“./MyComponent.js”)); Applying lazy loading Let us create a new react application to learn how to apply code splitting in this section. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a simple hello component, Hello (src/Components/Hello.js) and render a simple message as shown below − import React from “react”; class Hello extends React.Component { constructor(props) { super(props) } render() { return ( <div>Hello, {this.props.name}</div> ); } } export default Hello; Here, we have used the name props to render the hello message with the given name. Next, 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, open App component (src/App.js), and load the hello component through React.lazy() as shown below − import ”./App.css” import React, { Suspense, lazy } from ”react”; import SimpleErrorBoundary from ”./Components/SimpleErrorBoundary”; const Hello = lazy(() => import(”./Components/Hello”)); function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleErrorBoundary> <Suspense fallback=”<div>loading…</div>”> <Hello name=”Peter” /> </Suspense> </SimpleErrorBoundary> </div> </div> </div> ); } export default App; Here we have, Imported lazy and Suspense component from the react package. Used Hello component by wrapping it with Suspense and SimpleErrorBoundary component. Finally, open the application in the browser and check the final result. The lazy load does not have have any visible changes in the front end. It will render the