ReactJS – State Management ”; Previous Next State management is one of the important and unavoidable features of any dynamic application. React provides a simple and flexible API to support state management in a React component. Let us understand how to maintain state in React application in this chapter. What is state? State represents the value of a dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. The internal data represents the state of a React component and can be accessed using this.state member variable of the component. Whenever the state of the component is changed, the component will re-render itself by calling the render() method along with the new state. A simple example to better understand the state management is to analyse a real-time clock component. The clock component primary job is to show the date and time of a location at the given instance. As the current time will change every second, the clock component should maintain the current date and time in it”s state. As the state of the clock component changes every second, the clock”s render() method will be called every second and the render() method show the current time using it”s current state. The simple representation of the state is as follows − { date: ”2020-10-10 10:10:10” } Let us create a new Clock component in the Stateless Component chapter. Defining a State State in React can be used with functional and class components. To work with state in a component, there must exist a starting point, i.e. initial state. This initial state of a component must be defined in the constructor of the component”s class. Following is the syntax to define a state of any Class − state = {attribute: “value”}; Let us look at a sample code for a class component with an initial state − Class SampleClass extends React.Component { constructor(props) { super(props); this.state = { name : “John Doe” }; } } Creating a state Object React components have a built-in state object. The state object is used to store all the property values that belong to the component in which this state is defined. When the state object changes, the component re-renders. Let us look at a sample code to demonstrate how to create a state object in React. Class BookClass extends React.Component { constructor(props) { super(props); this.state = { name : “John Doe” }; } render() { return ( <div> <h1>Name of the Author</h1> </div> ); } } To understand state management better, check the following chapters. State management API State management using React Hooks Component Life cycle Component life cycle using React Hooks Layout in component Pagination Material UI Print Page Previous Next Advertisements ”;
Category: reactjs
ReactJS – Form Programming
ReactJS – Form Programming ”; Previous Next Forms are a common part of web applications which are mainly used allow users to interact with the application. These forms maybe included on the web page to gather information of the user, to let the user search a website, to make payments etc. The basic elements a form can contain are input fields, buttons, checklists, drop-down menus and so on. The data obtained from these forms is usually handled by components in React. To learn how to use forms in React, let us look at some examples. Form Programming Unlike HTML where forms get updated based on user input data, React updates the form with the help of its state. The mutable state is typically specified in the state property of components, and is only updated using setState(). The nature of form programming needs the state to be maintained. Because, the input field information will get changed as the user interacts with the form. But as we learned earlier, React library does not store or maintain any state information by itself and component has to use state management API to manage state. Considering this, React provides two types of components to support form programming. Controlled component − In controlled component, React provides a special attribute, value for all input elements and controls the input elements. The value attribute can be used to get and set the value of the input element. It has to be in sync with state of the component. Uncontrolled component − In uncontrolled component, React provides minimal support for form programming. It has to use Ref concept (another react concept to get a DOM element in the React component during runtime) to do the form programming. Let us learn the form programming using controlled as well as uncontrolled component in this chapter. Controlled component Uncontrolled Component Formik Print Page Previous Next Advertisements ”;
ReactJS – Material UI
ReactJS – Material UI ”; Previous Next React community provides a huge collection of advanced UI component framework. Material UI is one of the popular React UI frameworks. Let us learn how to use material UI library in this chapter. Installation Material UI can be installed using npm package. npm install @material-ui/core Material UI recommends roboto fonts for UI. To use Roboto font, include it using Gooogleapi links. <link rel=”stylesheet” href=”https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap” /> To use font icons, use icon link from googleapis − <link rel=”stylesheet” href=”https://fonts.googleapis.com/icon?family=Material+Icons” /> To use SVG icons, install @material-ui/icons package − npm install @material-ui/icons Working example Let us recreate the expense list application and use material ui components instead of html tables. Step 1 − First, create a new react application, react-materialui-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Step 2 − Install React Transition Group library − cd /go/to/project npm install @material-ui/core @material-ui/icons –save Open the application in your favorite editor. Create src folder under the root directory of the application. Create components folder under src folder. Create a file, ExpenseEntryItemList.js in src/components folder to create ExpenseEntryItemList component Import React library and the stylesheet. import React from ”react”; Step 2 − Next, import Material-UI library. import { withStyles } from ”@material-ui/core/styles”; import Table from ”@material-ui/core/Table”; import TableBody from ”@material-ui/core/TableBody”; import TableCell from ”@material-ui/core/TableCell”; import TableContainer from ”@material-ui/core/TableContainer”; import TableHead from ”@material-ui/core/TableHead”; import TableRow from ”@material-ui/core/TableRow”; import Paper from ”@material-ui/core/Paper”; Create ExpenseEntryItemList class and call constructor function. class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } } <link rel=”stylesheet” href=”https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap” /> Create a render() function. render() { } Apply styles for table rows and table cells in the render method. const StyledTableCell = withStyles((theme) => ({ head: { backgroundColor: theme.palette.common.black, color: theme.palette.common.white, }, body: { fontSize: 14, }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ root: { ”&:nth-of-type(odd)”: { backgroundColor: theme.palette.action.hover, }, }, }))(TableRow); Use map method to generate a collection of Material UI StyledTableRow each representing a single expense entry item in the list. const lists = this.props.items.map((item) => <StyledTableRow key={item.id}> <StyledTableCell component=”th” scope=”row”> {item.name} </StyledTableCell> <StyledTableCell align=”right”>{item.amount}</StyledTableCell> <StyledTableCell align=”right”> {new Date(item.spendDate).toDateString()} </StyledTableCell> <StyledTableCell align=”right”>{item.category}</StyledTableCell> </StyledTableRow> ); Here, key identifies each row and it has to be unique among the list. Step 3 − In the render() method, create a Material UI table and include the lists expression in the rows section and return it. return ( <TableContainer component={Paper}> <Table aria-label=”customized table”> <TableHead> <TableRow> <StyledTableCell>Title</StyledTableCell> <StyledTableCell align=”right”>Amount</StyledTableCell> <StyledTableCell align=”right”>Spend date</StyledTableCell> <StyledTableCell align=”right”>Category</StyledTableCell> </TableRow> </TableHead> <TableBody> {lists} </TableBody> </Table> </TableContainer> ); Finally, export the component. export default ExpenseEntryItemList; Now, we have successfully created the component to render the expense items using material ui components. The complete source code of the component is as given below − import React from ”react”; import { withStyles } from ”@material-ui/core/styles”; import Table from ”@material-ui/core/Table”; import TableBody from ”@material-ui/core/TableBody”; import TableCell from ”@material-ui/core/TableCell”; import TableContainer from ”@material-ui/core/TableContainer”; import TableHead from ”@material-ui/core/TableHead”; import TableRow from ”@material-ui/core/TableRow”; import Paper from ”@material-ui/core/Paper”; class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } render() { const StyledTableCell = withStyles((theme) => ({ head: { backgroundColor: theme.palette.common.black, color: theme.palette.common.white, }, body: { fontSize: 14, }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ root: { ”&:nth-of-type(odd)”: { backgroundColor: theme.palette.action.hover, }, }, }))(TableRow); const lists = this.props.items.map((item) => <StyledTableRow key={item.id}> <StyledTableCell component=”th” scope=”row”> {item.name} </StyledTableCell> <StyledTableCell align=”right”>{item.amount}</StyledTableCell> <StyledTableCell align=”right”>{new Date(item.spendDate).toDateString()}</StyledTableCell> <StyledTableCell align=”right”>{item.category}</StyledTableCell> </StyledTableRow> ); return ( <TableContainer component={Paper}> <Table aria-label=”customized table”> <TableHead> <TableRow> <StyledTableCell>Title</StyledTableCell> <StyledTableCell align=”right”>Amount</StyledTableCell> <StyledTableCell align=”right”>Spend date</StyledTableCell> <StyledTableCell align=”right”>Category</StyledTableCell> </TableRow> </TableHead> <TableBody> {lists} </TableBody> </Table> </TableContainer> ); } } export default ExpenseEntryItemList; index.js: Open index.js and import react library and our newly created ExpenseEntryItemList component. import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItemList from ”./components/ExpenseEntryItemList”; Declare a list (of expense entry item) and populate it with some random values in index.js file. const items = [ { id: 1, name: “Pizza”, amount: 80, spendDate: “2020-10-10”, category: “Food” }, { id: 1, name: “Grape Juice”, amount: 30, spendDate: “2020-10-12”, category: “Food” }, { id: 1, name: “Cinema”, amount: 210, spendDate: “2020-10-16”, category: “Entertainment” }, { id: 1, name: “Java Programming book”, amount: 242, spendDate: “2020-10-15”, category: “Academic” }, { id: 1, name: “Mango Juice”, amount: 35, spendDate: “2020-10-16”, category: “Food” }, { id: 1, name: “Dress”, amount: 2000, spendDate: “2020-10-25”, category: “Cloth” }, { id: 1, name: “Tour”, amount: 2555, spendDate: “2020-10-29”, category: “Entertainment” }, { id: 1, name: “Meals”, amount: 300, spendDate: “2020-10-30”, category: “Food” }, { id: 1, name: “Mobile”, amount: 3500, spendDate: “2020-11-02”, category: “Gadgets” }, { id: 1, name: “Exam Fees”, amount: 1245, spendDate: “2020-11-04”, category: “Academic” } ] Use ExpenseEntryItemList component by passing the items through items attributes. ReactDOM.render( <React.StrictMode> <ExpenseEntryItemList items={items} /> </React.StrictMode>, document.getElementById(”root”) ); The complete code of index.js is as follows − import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItemList from ”./components/ExpenseEntryItemList”; const items = [ { id: 1, name: “Pizza”, amount: 80, spendDate: “2020-10-10”, category: “Food” }, { id: 1, name: “Grape Juice”, amount: 30, spendDate: “2020-10-12”, category: “Food” }, { id: 1, name: “Cinema”, amount: 210, spendDate: “2020-10-16”, category: “Entertainment” }, { id: 1, name: “Java Programming book”, amount: 242, spendDate: “2020-10-15”, category: “Academic” }, { id: 1, name: “Mango Juice”, amount: 35, spendDate: “2020-10-16”, category: “Food” }, { id: 1, name: “Dress”, amount: 2000, spendDate: “2020-10-25”, category: “Cloth” }, { id: 1, name: “Tour”, amount: 2555, spendDate: “2020-10-29”, category: “Entertainment” }, { id: 1, name: “Meals”, amount: 300, spendDate: “2020-10-30”, category: “Food” }, { id: 1, name: “Mobile”, amount: 3500, spendDate:
ReactJS – Constructor
ReactJS – Constructor ”; Previous Next In general, constructor method in a class is used to set the initial value of the newly created object. React also use the constructor() for the same initialization purpose. Yet in react, constructor is used for state initialization and event binding purposes as well. Let us learn how to use constructor in the react component in this chapter. Initialization of props As we know, every react component will have props and state. The props should be initialized in the constructor using super keyword. If the props is not properly initialized in a class based react component, then this.props will not work properly and introduce bugs. Let us create a simple component with proper constructor method. class Welcome extends React.Component { constructor(props) { super(props); } render() { return ( <div><h3>Welcome {this.props.name}</h3></div> ) } } Here, super(props) will initialize the props in the Welcome component. this.props.* will provide access to props details. The component can be used as shown below − function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Welcome name={”John”} /> </div> </div> </div> ); } The component will render the welcome message as shown below − Initialization of the state Similar to props initialization, initialization of state is very important and can be done in the constructor. In general, React provides different ways to set and get the state information in a component. They are as follows − Using this.state = obj This is used to initialize the state using object this.state = { pageSize: 10 } Using this.state.* This is used to access the state information. (this.state.pageSize) Using this.setState() It is a function accepting either an object or a lambda function. Used to set the state information this.setState({ pageSize: 20 }) this.setState((state, props) => ({ pageSize: state.pageSize + 1 })) Let us create a simple component with proper state initialization class Welcome extends React.Component { constructor(props) { super(props); this.state = { welcomeMessage: “Hello” } } render() { return ( <div><h3>{this.state.welcomeMessage}, {this.props.name}</h3></div> ) } } Here, this.state is used to set the default (initial) value of the welcome message. The component can be used as shown below − function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Welcome name={”John”} /> </div> </div> </div> ); } The component will render the welcome message as shown below − Event binding Similar to props and state initialization, event handler has to be properly bind so that the this will be correctly accessed in the event handler. Let us create new button in our Welcome component to change the welcome message and add an event handler to handle the onClick event of the button as shown below − import React from “react”; class Welcome extends React.Component { constructor(props) { super(props); this.state = { welcomeMessage: “Hello” } this.changeMessageHandler = this.changeMessageHandler.bind(this) } changeMessageHandler() { this.setState(prevState => ({ welcomeMessage: prevState.welcomeMessage == “Hello” ? “Welcome” : “Hello” })); } render() { return ( <div> <div><h3>{this.state.welcomeMessage}, {this.props.name}</h3></div> <div><button onClick={this.changeMessageHandler}>Change welcome message</button></div> </div> ) } } export default Welcome; Here, Step1 − Add a button with an onClick event <div><button onClick={this.changeMessageHandler}>Change welcome message</button></div> Step 2 − Set this.changeMessageHandler method as onClick event handler Step 3 − Bind the event handler, this.changeMessageHandler in the constructor this.changeMessageHandler = this.changeMessageHandler.bind(this) Step 4 − Added the event handler and updated the state using this.setState. changeMessageHandler() { this.setState(prevState => ({ welcomeMessage: prevState.welcomeMessage == “Hello” ? “Welcome” : “Hello” })); } The component can be used as shown below − function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Welcome name={”John”} /> </div> </div> </div> ); } The component will render the welcome message as shown below − Summary Constructor is very important in the class based react component. It”s main job is to setup the component in such a way that the props, state and events are configured correctly and ready to access by the component events and render methods. Print Page Previous Next Advertisements ”;
ReactJS – Creating a React Application ”; Previous Next As we learned earlier, React library can be used in both simple and complex application. Simple application normally includes the React library in its script section. In complex application, developers have to split the code into multiple files and organize the code into a standard structure. Here, React toolchain provides pre-defined structure to bootstrap the application. Also, developers are free to use their own project structure to organize the code. Let us see how to create simple as well as complex React application − Simple application using CDN Complex application using React Create App cli Complex application using customized method Using Rollup bundler Rollup is one of the small and fast JavaScript bundlers. Let us learn how to use rollup bundler in this chapter. Following are the steps to creating an application using Rollup bundler − Step 1 − Open a terminal and go to your workspace. cd /go/to/your/workspace Step 2 − Next, create a folder, expense-manager-rollup and move to newly created folder. Also, open the folder in your favorite editor or IDE. mkdir expense-manager-rollup cd expense-manager-rollup Then, create and initialize the project. npm init -y Step 3 − To install React libraries (react and react-dom), follow the command below. npm install react@^17.0.0 react-dom@^17.0.0 –save Then install babel and its preset libraries as development dependency using the following commands. npm install @babel/preset-env @babel/preset-react @babel/core @babel/plugin-proposal-class-properties -D Next, install rollup and its plugin libraries as development dependency. npm i -D rollup [email protected] @rollup/plugin-babel @rollup/plugin-commonjs @rollup/plugin-node-resolve @rollup/plugin-replace rollup-plugin-livereload rollup-plugin-postcss rollup-plugin-serve [email protected] postcss-modules@4 rollup-plugin-postcss Next, install corejs and regenerator runtime for async programming. npm i regenerator-runtime core-js Step 4 − Later, create a babel configuration file, .babelrc under the root folder to configure the babel compiler. { “presets”: [ [ “@babel/preset-env”, { “useBuiltIns”: “usage”, “corejs”: 3, “targets”: “> 0.25%, not dead” } ], “@babel/preset-react” ], “plugins”: [ “@babel/plugin-proposal-class-properties” ] } rollup.config.js: Next, create a rollup.config.js file in the root folder to configure the rollup bundler. import babel from ”@rollup/plugin-babel”; import resolve from ”@rollup/plugin-node-resolve”; import commonjs from ”@rollup/plugin-commonjs”; import replace from ”@rollup/plugin-replace”; import serve from ”rollup-plugin-serve”; import livereload from ”rollup-plugin-livereload”; import postcss from ”rollup-plugin-postcss” export default { input: ”src/index.js”, output: { file: ”public/index.js”, format: ”iife”, }, plugins: [ commonjs({ include: [ ”node_modules/**”, ], exclude: [ ”node_modules/process-es6/**”, ], }), resolve(), babel({ exclude: ”node_modules/**” }), replace({ ”process.env.NODE_ENV”: JSON.stringify(”production”), }), postcss({ autoModules: true }), livereload(”public”), serve({ contentBase: ”public”, port: 3000, open: true, }), // index.html should be in root of project ] } package.json Next, update the package.json and include our entry point (public/index.js and public/styles.css) and command to build and run the application. … “main”: “public/index.js”, “style”: “public/styles.css”, “files”: [ “public” ], “scripts”: { “start”: “rollup -c -w”, “build”: “rollup” }, … Step 5 − Next, create a src folder in the root directory of the application, which will hold all the source code of the application. Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles. The final structure of the application will be as follows − |– package-lock.json |– package.json |– rollup.config.js |– .babelrc `– public |– index.html `– src |– index.js `– components | |– mycom.js | |– mycom.css Now, let us create a new component, HelloWorld to confirm our setup is working fine. HelloWorld.js Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message. import React from “react”; class HelloWorld extends React.Component { render() { return ( <div> <h1>Hello World!</h1> </div> ); } } export default HelloWorld; index.js Next, create our main file, index.js under src folder and call our newly created component. import React from ”react”; import ReactDOM from ”react-dom”; import HelloWorld from ”./components/HelloWorld”; ReactDOM.render( <React.StrictMode> <HelloWorld /> </React.StrictMode>, document.getElementById(”root”) ); Create a public folder in the root directory. index.html Next, create a html file, index.html (under public folder*), which will be our entry point of the application. <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”utf-8″> <title>Expense Manager :: Rollup version</title> </head> <body> <div id=”root”></div> <script type=”text/JavaScript” src=”./index.js”></script> </body> </html> Lastly, build and run the application. npm start The npm build command will execute the rollup and bundle our application into a single file, dist/index.js file and start serving the application. The dev command will recompile the code whenever the source code is changed and also reload the changes in the browser. > [email protected] build /path/to/your/workspace/expense-manager-rollup > rollup -c rollup v2.36.1 bundles src/index.js → distindex.js… LiveReload enabled http://localhost:10001 -> /path/to/your/workspace/expense-manager-rollup/dist created distindex.js in 4.7s waiting for changes… Open the browser and enter http://localhost:3000 in the address bar and press enter. serve application will serve our webpage as shown below. Using Parcel bundler Parcel is fast bundler with zero configuration. It expects just the entry point of the application and it will resolve the dependency itself and bundle the application. Let us learn how to use parcel bundler in this chapter. Step 1 − First, install the parcel bundler. npm install -g parcel-bundler Then, open a terminal and go to your workspace. cd /go/to/your/workspace Step 2 − Next, create a folder, expense-manager-parcel and move to newly created folder. Also, open the folder in your favorite editor or IDE. mkdir expense-manager-parcel cd expense-manager-parcel Create and initialize the project using the following command. npm init -y Step 3 − Install
ReactJS – Components
ReactJS – Component ”; Previous Next React component is the building block of a React application. Let us learn how to create a new React component and the features of React components in this chapter. 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. Initial rendering of the user interface. Management and handling of events. Updating the user interface whenever the internal state is changed. React component accomplish these feature using three concepts − Properties − Enables the component to receive input. Events − Enable the component to manage DOM events and end-user interaction. State − Enable the component to stay stateful. Stateful component updates its UI with respect to its state. There are two types of components in React. They are − Function Components Class Components Function Components A function component is literally defined as JavaScript functions. This React component accepts a single object argument and returns a React element. Note that an element in React is not a component, but a component is comprised of multiple elements. Following is the syntax for the function component in React: function function_name(argument_name) { function_body; } Class Components Similarly, class components are basic classes that are made of multiple functions. All class components of React are subclasses of the React.Component class, hence, a class component must always extend it. Following is the basic syntax − class class_name extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } Let us learn all the concept one-by-one in the upcoming chapters. Creating a React component React library has two component types. The types are categorized based on the way it is being created. Function component − Uses plain JavaScript function. ES6 class component − Uses ES6 class. The core difference between function and class component are − Function components are very minimal in nature. Its only requirement is to return a React element. function Hello() { return ”<div>Hello</div>” } The same functionality can be done using ES6 class component with little extra coding. class ExpenseEntryItem extends React.Component { render() { return ( <div>Hello</div> ); } } Class components supports state management out of the box whereas function components does not support state management. But, React provides a hook, useState() for the function components to maintain its state. Class component have a life cycle and access to each life cycle events through dedicated callback apis. Function component does not have life cycle. Again, React provides a hook, useEffect() for the function component to access different stages of the component. Creating a class component Let us create a new React component (in our expense-manager app), ExpenseEntryItem to showcase an expense entry item. Expense entry item consists of name, amount, date and category. The object representation of the expense entry item is − { ”name”: ”Mango juice”, ”amount”: 30.00, ”spend_date”: ”2020-10-10” ”category”: ”Food”, } Open expense-manager application in your favorite editor. Next, create a file, ExpenseEntryItem.css under src/components folder to style our component. Next, create a file, ExpenseEntryItem.js under src/components folder by extending React.Component. import React from ”react”; import ”./ExpenseEntryItem.css”; class ExpenseEntryItem extends React.Component { } Next, create a method render inside the ExpenseEntryItem class. class ExpenseEntryItem extends React.Component { render() { } } Next, create the user interface using JSX and return it from render method. class ExpenseEntryItem extends React.Component { render() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } Next, specify the component as default export class. import React from ”react”; import ”./ExpenseEntryItem.css”; class ExpenseEntryItem extends React.Component { render() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } export default ExpenseEntryItem; Now, we successfully created our first React component. Let us use our newly created component in index.js. import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItem from ”./components/ExpenseEntryItem” ReactDOM.render( <React.StrictMode> <ExpenseEntryItem /> </React.StrictMode>, document.getElementById(”root”) ); Example The same functionality can be done in a webpage using CDN as shown below − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>React application :: ExpenseEntryItem component</title> </head> <body> <div id=”react-app”></div> <script src=”https://unpkg.com/react@17/umd/react.development.js” crossorigin></script> <script src=”https://unpkg.com/react-dom@17/umd/react-dom.development.js” crossorigin></script> <script src=”https://unpkg.com/@babel/standalone/babel.min.js”></script> <script type=”text/babel”> class ExpenseEntryItem extends React.Component { render() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } ReactDOM.render( <ExpenseEntryItem />, document.getElementById(”react-app”) ); </script> </body> </html> Next, serve the application using npm command. npm start Output Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Item: Mango Juice Amount: 30.00 Spend Date: 2020-10-10 Category: Food Creating a function component React component can also be created using plain JavaScript function but with limited features. Function based React component does not support state management and other advanced features. It can be used to quickly create a simple component. The above ExpenseEntryItem can be rewritten in function as specified below − function ExpenseEntryItem() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } Here, we just included the render functionality and it is enough to create a simple React component. Splitting Components
ReactJS – Component Life Cycle ”; Previous Next In React, Life cycle of a component represents the different stages of the component during its existence. React provides callback function to attach functionality in each and every stages of the React life cycle. Let us learn the life cycle (and the related API) of a React component in this chapter. Life cycle API Each React component has three distinct stages. Mounting − Mounting represents the rendering of the React component in the given DOM node. Updating − Updating represents the re-rendering of the React component in the given DOM node during state changes / updates. Unmounting − Unmounting represents the removal of the React component. React provides a collection of life cycle events (or callback API) to attach functionality, which will to be executed during the various stages of the component. The visualization of life cycle and the sequence in which the life cycle events (APIs) are invoked as shown below. constructor() − Invoked during the initial construction phase of the React component. Used to set initial state and properties of the component. render() − Invoked after the construction of the component is completed. It renders the component in the virtual DOM instance. This is specified as mounting of the component in the DOM tree. componentDidMount() − Invoked after the initial mounting of the component in the DOM tree. It is the good place to call API endpoints and to do network requests. In our clock component, setInterval function can be set here to update the state (current date and time) for every second. componentDidMount() { this.timeFn = setInterval( () => this.setTime(), 1000); } componentDidUpdate() − Similar to ComponentDidMount() but invoked during the update phase. Network request can be done during this phase but only when there is difference in component”s current and previous properties. The signature of the API is as follows − componentDidUpdate(prevProps, prevState, snapshot) prevProps − Previous properties of the component. prevState − Previous state of the component. snapshot − Current rendered content. componentWillUnmount() − Invoked after the component is unmounted from the DOM. This is the good place to clean up the object. In our clock example, we can stop updating the date and time in this phase. componentDidMount() { this.timeFn = setInterval( () => this.setTime(), 1000); } shouldComponentUpdate() − Invoked during the update phase. Used to specify whether the component should update or not. If it returns false, then the update will not happen. The signature is as follows − shouldComponentUpdate(nextProps, nextState) nextProps − Upcoming properties of the component nextState − Upcoming state of the component getDerivedStateFromProps − Invoked during both initial and update phase and just before the render() method. It returns the new state object. It is rarely used where the changes in properties results in state change. It is mostly used in animation context where the various state of the component is needed to do smooth animation. The signature of the API is as follows − static getDerivedStateFromProps(props, state) props − current properties of the component state − Current state of the component This is a static method and does not have access to this object. getSnapshotBeforeUpdate − Invoked just before the rendered content is commited to DOM tree. It is mainly used to get some information about the new content. The data returned by this method will be passed to ComponentDidUpdate() method. For example, it is used to maintain the user”s scroll position in the newly generated content. It returns user”s scroll position. This scroll position is used by componentDidUpdate() to set the scroll position of the output in the actual DOM. The signature of the API is as follows − getSnapshotBeforeUpdate(prevProps, prevState) prevProps − Previous properties of the component. prevState − Previous state of the component. Working example of life cycle API Let us use life cycle api in our react-clock-app application. Step 1 − Open react-clock-hook-app in your favorite editor. Open src/components/Clock.js file and start editing. Step 2 − Remove the setInterval() method from the constructor. constructor(props) { super(props); this.state = { date: new Date() } } Step 3 − Add componentDidMount() method and call setInterval() to update the date and time every second. Also, store the reference to stop updating the date and time later. componentDidMount() { this.setTimeRef = setInterval(() => this.setTime(), 1000); } Add componentWillUnmount() method and call clearInterval() to stop the date and time update calls. componentWillUnmount() { clearInterval(this.setTimeRef) } Now, we have updated the Clock component and the complete source code of the component is given below − import React from ”react”; class Clock extends React.Component { constructor(props) { super(props); this.state = { date: new Date() } } componentDidMount() { this.setTimeRef = setInterval(() => this.setTime(), 1000); } componentWillUnmount() { clearInterval(this.setTimeRef) } setTime() { this.setState((state, props) => { console.log(state.date); return { date: new Date() } }) } render() { return ( <div> <p>The current time is {this.state.date.toString()}</p> </div> ); } } export default Clock; Next, open index.js and use setTimeout to remove the clock from the DOM after 5 seconds. import React from ”react”; import ReactDOM from ”react-dom”; import Clock from ”./components/Clock”; ReactDOM.render( <React.StrictMode> <Clock /> </React.StrictMode>, document.getElementById(”root”) ); setTimeout(() => { ReactDOM.render( <React.StrictMode> <div><p>Clock is removed from the DOM.</p></div> </React.StrictMode>, document.getElementById(”root”) ); }, 5000); Serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. The clock will be shown for 5 second and then, it will
ReactJS – Create an Event-Aware Component ”; Previous Next Event management is one of the important features in a web application. It enables the user to interact with the application. React supports all events available in a web application. React event handling is very similar to DOM events with little changes. For example, clicking on a component is one of the common events one can observe in React-based websites. An event-aware component in React is nothing but a component that contains an event handler method within it. The component can either be a class component or functional component. In this chapter, we will learn how to create such event-aware components with React. How to create an Event-Aware Component? Following are the steps to create a new Event-Aware Component − Let us create a new component, MessageWithEvent and handle events in the component to better understand event management in React application. Step 1 − Open expense-manager application in your favorite editor. Next, create a file, MessageWithEvent.js in src/components folder to create MessageWithEvent component. Import React library. import React from ”react”; Step 2 − Create a class, MessageWithEvent and call constructor with props. class MessageWithEvent extends React.Component { constructor(props) { super(props); } } Step 3 − Create an event handler method, logEventToConsole, which will log event details to the console. logEventToConsole(e) { console.log(e.target.innerHTML); } Step 4 − Create a render function. render() { } In render() function, create a greeting message and return it. render() { return ( <div> <p>Hello {this.props.name}!</p> </div> ); } Step 5 − Then, set logEventToConsole method as the event handler for click event of the root container(div). render() { return ( <div onClick={this.logEventToConsole}> <p>Hello {this.props.name}!</p> </div> ); } Step 6 − Update the constructor by binding the event handler. class MessageWithEvent extends React.Component { constructor(props) { super(props); this.logEventToConsole = this.logEventToConsole.bind(); } } Finally, export the component. export default MessageWithEvent; The complete code of the MessageWithEvent component is given below − import React from ”react”; class MessageWithEvent extends React.Component { constructor(props) { super(props); this.logEventToConsole = this.logEventToConsole.bind(); } logEventToConsole(e) { console.log(e.target.innerHTML); } render() { return ( <div onClick={this.logEventToConsole}> <p>Hello {this.props.name}!</p> </div> ); } } export default MessageWithEvent; index.js Next, open index.js and import MessageWithEvent. import MessageWithEvent from ”./components/MessageWithEvent” Build the user interface of the application by using MessageWithEvent component. import React from ”react”; import ReactDOM from ”react-dom”; import MessageWithEvent from ”./components/MessageWithEvent” ReactDOM.render( <React.StrictMode> <div> <MessageWithEvent name=”React” /> <MessageWithEvent name=”React developer” /> </div> </React.StrictMode>, document.getElementById(”root”) ); Serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. Now, click both MessageWithEvent component and the application will emit messages in the console as shown below. Passing Extra Information to Event Handler Let us try to pass and an extra information (for example, msgid) to event handler. Step 1 − First, update the logEventToConsole to accept an extra argument, msgid. logEventToConsole(msgid, e) { console.log(e.target.innerHTML); console.log(msgid); } Step 2 − Next, pass message id to the event handler by binding the message id in the render method. render() { return ( <div onClick={this.logEventToConsole.bind(this, Math.floor(Math.random() * 10))}> <p>Hello {this.props.name}!</p> </div> ); } Step 3 − The complete and updated code is as follows − import React from ”react”; class MessageWithEvent extends React.Component { constructor(props) { super(props); this.logEventToConsole = this.logEventToConsole.bind(); } logEventToConsole(msgid, e) { console.log(e.target.innerHTML); console.log(msgid); } render() { return ( >div onClick={this.logEventToConsole.bind(this, Math.floor(Math.random() * 10))}> >p>Hello {this.props.name}!>/p> >/div> ); } } export default MessageWithEvent; Run the application and you will find that the event emits message id in the console. Print Page Previous Next Advertisements ”;
ReactJS – Installation
ReactJS – Installation ”; Previous Next This chapter explains the installation of React library and its related tools in your machine. Before moving to the installation, let us verify the prerequisite first. React provides CLI tools for the developer to fast forward the creation, development and deployment of the React based web application. React CLI tools depends on the Node.js and must be installed in your system. Hopefully, you have installed Node.js on your machine. We can check it using the below command − node –version You could see the version of Nodejs you might have installed. It is shown as below for me, v14.2.0 If Nodejs is not installed, you can download and install by visiting https://nodejs.org/en/download/. Toolchain To develop lightweight features such as form validation, model dialog, etc., React library can be directly included into the web application through content delivery network (CDN). It is similar to using jQuery library in a web application. For moderate to big application, it is advised to write the application as multiple files and then use bundler such as webpack, parcel, rollup, etc., to compile and bundle the application before deploying the code. React toolchain helps to create, build, run and deploy the React application. React toolchain basically provides a starter project template with all necessary code to bootstrap the application. Some of the popular toolchain to develop React applications are − Create React App − SPA oriented toolchain Next.js − server-side rendering oriented toolchain Gatsby − Static content oriented toolchain Tools required to develop a React application are − The serve, a static server to serve our application during development Babel compiler Create React App CLI Let us learn the basics of the above mentioned tools and how to install those in this chapter. The serve static server The serve is a lightweight web server. It serves static site and single page application. It loads fast and consume minimum memory. It can be used to serve a React application. Let us install the tool using npm package manager in our system. npm install serve -g Let us create a simple static site and serve the application using serve app. Open a command prompt and go to your workspace. cd /go/to/your/workspace Create a new folder, static_site and change directory to newly created folder. mkdir static_site cd static_site Next, create a simple webpage inside the folder using your favorite html editor. <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>Static website</title> </head> <body> <div><h1>Hello!</h1></div> </body> </html> Next, run the serve command. serve . We can also serve single file, index.html instead of the whole folder. serve ./index.html Next, open the browser and enter http://localhost:5000 in the address bar and press enter. serve application will serve our webpage as shown below. The serve will serve the application using default port, 5000. If it is not available, it will pick up a random port and specify it. │ Serving! │ │ │ │ – Local: http://localhost:57311 │ │ – On Your Network: http://192.168.56.1:57311 │ │ │ │ This port was picked because 5000 is in use. │ │ │ │ Copied local address to clipboard! Babel compiler Babel is a JavaScript compiler which compiles many variant (es2015, es6, etc.,) of JavaScript into standard JavaScript code supported by all browsers. React uses JSX, an extension of JavaScript to design the user interface code. Babel is used to compile the JSX code into JavaScript code. To install Babel and it”s React companion, run the below command − npm install babel-cli@6 babel-preset-react-app@3 -g … … + [email protected] + [email protected] updated 2 packages in 8.685s Babel helps us to write our application in next generation of advanced JavaScript syntax. Create React App toolchain Create React App is a modern CLI tool to create single page React application. It is the standard tool supported by React community. It handles babel compiler as well. Let us install Create React App in our local system. > npm install -g create-react-app + [email protected] added 6 packages from 4 contributors, removed 37 packages and updated 12 packages in 4.693s Updating the toolchain React Create App toolchain uses the react-scripts package to build and run the application. Once we started working on the application, we can update the react-script to the latest version at any time using npm package manager. npm install react-scripts@latest Advantages of using React toolchain React toolchain provides lot of features out of the box. Some of the advantages of using React toolchain are − Predefined and standard structure of the application. Ready-made project template for different type of application. Development web server is included. Easy way to include third party React components. Default setup to test the application. Print Page Previous Next Advertisements ”;
ReactJS – Nested Components
ReactJS – Nested Components ”; Previous Next A nested component in React is a component that is related to an another component. You can also consider it as a child component inside a parent component; but they are not linked together using the inheritance concept but with the composition concept. Therefore, all the components are nested together in order to create a bigger component rather than a smaller component inheriting from the parent component. The React component is a building block of a React application. A React component is made up of the multiple individual components. React allows multiple components to be combined to create larger components. Also, React components can be nested to any arbitrary level. Nested components will make your code more efficient and structured. However, if the components are not nested or assembled properly, there is chance your code can become more complex resulting in lower efficiency. Let us see how React components can be composed properly in this chapter. FormattedMoney component Let us create a component, FormattedMoney to format the amount to two decimal places before rendering. Step 1 − Open our expense-manager application in your favourite editor. Create a file named FormattedMoney.js in the src/components folder and, Import React library. import React from ”react”; Step 2 − Then create a class, FormattedMoney by extending React.Component. class FormattedMoney extends React.Component { } Next, introduce construction function with argument props as shown below − constructor(props) { super(props); } Create a method format() to format the amount. format(amount) { return parseFloat(amount).toFixed(2) } Create another method render() to emit the formatted amount. render() { return ( <span>{this.format(this.props.value)}</span> ); } Here, we have used the format method by passing value attribute through this.props. Step 3 − Next, specify the component as default export class. export default FormattedMoney; Now, we have successfully created our FormattedMoney React component. import React from ”react”; class FormattedMoney extends React.Component { constructor(props) { super(props) } format(amount) { return parseFloat(amount).toFixed(2) } render() { return ( <span>{this.format(this.props.value)}</span> ); } } export default FormattedMoney; FormattedDate Component Let us create another component, FormattedDate to format and show the date and time of the expense. Step 1 − Open our expense-manager application in your favorite editor. Create a file, FormattedDate.js in the src/components folder and import React library. import React from ”react”; Step 2 − Next, create a class by extending React.Component. class FormattedDate extends React.Component { } Then introduce construction function with argument props as shown below − constructor(props) { super(props); } Step 3 − Next, create a method format() to format the date. format(val) { const months = [“JAN”, “FEB”, “MAR”,”APR”, “MAY”, “JUN”, “JUL”, “AUG”, “SEP”, “OCT”, “NOV”, “DEC”]; let parsed_date = new Date(Date.parse(val)); let formatted_date = parsed_date.getDate() + “-” + months[parsed_date.getMonth()] + “-” + parsed_date.getFullYear() return formatted_date; } Create another method render() to emit the formatted date. render() { return ( <span>{this.format(this.props.value)}</span> ); } Here, we have used the format method by passing value attribute through this.props. Step 4 − Next, specify the component as default export class. export default FormattedDate; Now, we have successfully created our FormattedDate React component. The complete code is as follows − import React from ”react”; class FormattedDate extends React.Component { constructor(props) { super(props) } format(val) { const months = [“JAN”, “FEB”, “MAR”,”APR”, “MAY”, “JUN”, “JUL”, “AUG”, “SEP”, “OCT”, “NOV”, “DEC”]; let parsed_date = new Date(Date.parse(val)); let formatted_date = parsed_date.getDate() + “-” + months[parsed_date.getMonth()] + “-” + parsed_date.getFullYear() return formatted_date; } render() { return ( <span>{this.format(this.props.value)}</span> ); } } export default FormattedDate; Print Page Previous Next Advertisements ”;