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:
Category: reactjs
ReactJS – Conditional Rendering ”; Previous Next Conditional rendering in React Conditional rendering is used to show / hide a certain part of the UI to the user depending on the situation. For example, if the user is not logged into a web application, the web application will show the login button. When the user logged into the web application, the same link will be replaced by the welcome message. Let us learn the options provided by the React to support conditional rendering. Methods of conditional rendering React provides multiple ways to do conditional rendering in a web application. They are as follows − Conditional statement JSX / UI variable Logical && operator in JSX Conditional operator in JSX null return value Conditional statement Conditional statement is simple and straight forward option to render a UI based on a condition. Let us consider that the requirement is to write a component which will show either login link or welcome message based on the user”s login status. Below is the implementation of the component using conditional rendering, function Welcome(props) { if(props.isLoggedIn) { return <div>Welcome, {props.userName}</div> } else { return <div><a href=”/login”>Login</a></div> } } Here, Used isLoggedIn props to check whether the user is already logged in or not. Returned welcome message, if the user is already logged in. Returned login link, if the user is not logged in. The component can be used as shown below C− function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Welcome isLoggedIn={true} userName={”John”} /> </div> </div> </div> ); } The component will render the welcome message as shown below − JSX / UI variable React allows the storing of JSX element into a variable and use it whenever necessary. Developer can create the necessary JSX through conditional statement and store it in a variable. Once the UI is stored in a variable, it can be rendered as shown below − function Welcome(props) { let output = null; if(props.isLoggedIn) { output = <div>Welcome, {props.userName}</div> } else { output = <div><a href=”/login”>Login</a></div> } return output } Here, we have used the variable output to hold the UI. The component can be used as shown below − function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Welcome isLoggedIn={true} userName={”John”} /> </div> </div> </div> ); } The component will render the welcome message as shown below − Logical && operator React allows any expression to be used in the JSX code. In Javascript, condition are applied from left to right. If the left most condition is false, then the next condition will not be processed. Developer can utilize this feature and output the message in the JSX itself as shown below − function ShowUsers(props) { return ( <div> <ul> {props.users && props.users.length > 0 && props.users.map((item) => ( <li>{item}</li> ) )} </ul> </div> ); } export default ShowUsers; Here, First of all, props.users will be checked for availability. If props.users is null, then the condition will not be processed further Once, props.users is available, then the length of the array will be checked and only if the length is greater then zero, the condition will be processed further Finally, props.users will be looped over through map function and the users information will be rendered as unordered list. The component can be used as shown below − function App() { const users = [”John”, ”Peter”] return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <ShowUsers users={users} /> </div> </div> </div> ); } The component will render the users as shown below − Conditional operator in JSX Since React allows any javascript expression in JSX, developer can use conditional operator (a =b ? x : y) in the JSX and render the necessary UI element only as shown below − function Welcome(props) { if(props.isLoggedIn) { return props.isLoggedIn ? <div>Welcome, {props.userName}</div> : <div><a href=”/login”>Login</a></div> } } Here, we have used the conditional operator to show either welcome message or login link. The component can be used as shown below − function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Welcome isLoggedIn={true} userName={”John”} /> </div> </div> </div> ); } The component will render the welcome message as shown below − The null return value React renders a component only when the component returns a UI element. Otherwise, it silently skip the rendering without any error message. Developer can exploit this feature and render certain UI only when a condition is met. function Welcome(props) { return props.isLoggedIn ? <div>Welcome, {props.userName}</div> : null } Here, We have used conditional operator to either show / hide the welcome message null does not render any UI The component can be used as shown below − function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <div>Welcome component will not output any content</div> <Welcome isLoggedIn={false} /> </div> </div> </div> </div> ); } The component will render the welcome message as shown below − Summary React provides multiple way to conditionally render a UI element. Method has to be chosen by the developer by analyzing the situation Print Page Previous Next Advertisements ”;
ReactJS – Lists
ReactJS – Lists ”; Previous Next List and For The most common pattern in React is to convert a collection of items into to React elements. JavaScript has lot of option to manipulate the collection. Let us see how to use collection using for loop in this chapter. for loop The simple and easy solution to use is the time tested for loop to loop over the collection and use JSX expression to create the final React elements. Let us create a React app and try to apply for loop. Create a new application using create-react-app and start the application. create-react-app myapp cd myapp npm start Next, create a component, ExpenseListUsingForLoop under components folder (src/components/ExpenseListUsingForLoop.js) import React from ”react” class ExpenseListUsingForLoop extends React.Component { render() { return <table> <thead> <tr> <th>Item</th> <th>Amount</th> </tr> </thead> <tbody> </tbody> <tfoot> <tr> <th>Sum</th> <th></th> </tr> </tfoot> </table> } } export default ExpenseListUsingForLoop Here, we created a basic table structure with header and footer. Next, create a function to find the total expense amount. We will use it later in the render() method. getTotalExpenses() { var items = this.props[”expenses”]; var total = 0; for(let i = 0; i < items.length; i++) { total += parseInt(items[i]); } return total; } Here, getTotalExpenses loop over the expense props and summarize the total expenses. Then, add expense items and total amount in the render method. render() { var items = this.props[”expenses”]; var expenses = [] for(let i = 0; i < items.length; i++) { expenses.push(<tr><td>item {i + 1}</td><td>{items[i]}</td></tr>) } var total = this.getTotalExpenses(); return <table> <thead> <tr> <th>Item</th> <th>Amount</th> </tr> </thead> <tbody> {expenses} </tbody> <tfoot> <tr> <th>Sum</th> <th>{total}</th> </tr> </tfoot> </table> } Here, Navigated each item in the expense array using for loop, generated table row (tr) using JSX and finally pushed it into expenses array. We have used expenses array in the JSX expression to include the generated rows. The getTotalExpenses method to find the total expense amount and add it into the render method. The complete source code of the ExpenseListUsingForLoop component is as follows − import React from ”react” class ExpenseListUsingForLoop extends React.Component { getTotalExpenses() { var items = this.props[”expenses”]; var total = 0; for(let i = 0; i < items.length; i++) { total += parseInt(items[i]); } return total; } render() { var items = this.props[”expenses”]; var expenses = [] for(let i = 0; i < items.length; i++) { expenses.push(<tr><td>item {i + 1}</td><td>{items[i]}</td></tr>) } var total = this.getTotalExpenses(); return <table> <thead> <tr> <th>Item</th> <th>Amount</th> </tr> </thead> <tbody> {expenses} </tbody> <tfoot> <tr> <th>Sum</th> <th>{total}</th> </tr> </tfoot> </table> } } export default ExpenseListUsingForLoop Next, update the App component (App.js) with ExpenseListUsingForLoop component. import ExpenseListUsingForLoop from ”./components/ExpenseListUsingForLoop”; import ”./App.css”; function App() { var expenses = [100, 200, 300] return ( <div> <ExpenseListUsingForLoop expenses={expenses} /> </div> ); } export default App; Next, add include a basic styles in App.css /* Center tables for demo */ table { margin: 0 auto; } div { padding: 5px; } /* Default Table Style */ table { color: #333; background: white; border: 1px solid grey; font-size: 12pt; border-collapse: collapse; } table thead th, table tfoot th { color: #777; background: rgba(0,0,0,.1); text-align: left; } table caption { padding:.5em; } table th, table td { padding: .5em; border: 1px solid lightgrey; } Finally, check the application in the browser. It will show the expenses as shown below − ECMASCript 6 for loop Let us change the application and use the for .. of loop introduced in ECMAScript 6. for(const [idx, item] of items.entries()) { expenses.push(<tr><td>item {idx + 1}</td><td>{item}</td></tr>) } Here, idx refers the index of the array. item refers expense item in each position of the array. entries method parses the array and return it as an array of key-value pair. key refers the index of the array and value refers the value of the array in the corresponding key. If we don”t need index, then we can skip entries() method as shown below − for(const item of items) { expenses.push(<tr><td></td><td>{item}</td></tr>) } Print Page Previous Next Advertisements ”;
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 – Features
ReactJS – Features ”; Previous Next ReactJS slowly becoming one of the best JavaScript framework among web developers. It is playing an essential role in the front-end ecosystem. Following are the important features of ReactJS Virtual DOM Components JSX One way data binding Scalable Flexible Modular Virtual DOM Virtual DOM is a special DOM created by React. Virtual DOM represents the real DOM of the current HTML document. Whenever there is a change in the HTML document, React checks the updated virtual DOM with the previous state of the Virtual DOM and update only the different in th actual / real DOM. This improves the performance of the rendering of the HTML document. For example, if we create a React component to show the current time by periodically updating the time through setInterval() method, then React will update only the current time instead of updating the whole content of the component. Components React is build upon the concept of components. All modern front end framework relies on the component architecture. Component architecture enables the developer to break down the large application into smaller components, which can be further break down into even smaller component. Breaking down the application into smaller component simplifies the application and make it more understandable and manageable. JSX JSX is a JavaScript extension to create arbitrary HTML element using syntax similar to HTML. This will simplify the HTML document creation as well as easy to understand the document. React will convert the JSX into JavaScript object consisting of React”s createElement() function call before executing it. It improves the performance of the application. Also, React allows the HTML document creation using pure createElement() function without JSX as well. This enables the developer to directly create HTML document in a situation where JSX does not fit well. One way data binding One way data binding prevents the data in a component to flow backward. A component can pass the data to its child component only. The data cannot be passed by a component to its parent component in any situation. This will simplify the data handling and reduce the complexity. Two way data binding may seems mandatory at first but a closer look suggests that the application can be done with one way data binding only and this simplifies the application concept as well. Scalable React can be used to create application of any size. React component architecture, Virtual DOM and one way data binding properly handle large application in a reasonable time frame required for a front end application. These features make React a scalable solution. Flexible React only provides only few basic concept to create truly scalable application. React does not restrict the developer in any way to follow a rigid process. This enables the developer to apply their own architecture on top the basic concept and makes it flexible. Modular React component can be created in a separate JavaScript file and can be made exportable. This enables the developer to categories and group certain components into a module so that it can be imported and used wherever needed. Print Page Previous Next Advertisements ”;
ReactJS – Architecture
ReactJS – Architecture ”; Previous Next React library is built on a solid foundation. It is simple, flexible and extensible. As we learned earlier, React is a library to create user interface in a web application. React”s primary purpose is to enable the developer to create user interface using pure JavaScript. Normally, every user interface library introduces a new template language (which we need to learn) to design the user interface and provides an option to write logic, either inside the template or separately. Instead of introducing new template language, React introduces three simple concepts as given below − React elements JavaScript representation of HTML DOM. React provides an API, React.createElement to create React Element. JSX A JavaScript extension to design user interface. JSX is an XML based, extensible language supporting HTML syntax with little modification. JSX can be compiled to React Elements and used to create user interface. React component React component is the primary building block of the React application. It uses React elements and JSX to design its user interface. React component is basically a JavaScript class (extends the React.component class) or pure JavaScript function. React component has properties, state management, life cycle and event handler. React component can be able to do simple as well as advanced logic. Let us learn more about components in the React Component chapter. Architecture of the React Application React library is just UI library and it does not enforce any particular pattern to write a complex application. Developers are free to choose the design pattern of their choice. React community advocates certain design pattern. One of the patterns is Flux pattern. React library also provides lot of concepts like Higher Order component, Context, Render props, Refs etc., to write better code. React Hooks is evolving concept to do state management in big projects. Let us try to understand the high level architecture of a React application. React app starts with a single root component. Root component is build using one or more component. Each component can be nested with other component to any level. Composition is one of the core concepts of React library. So, each component is build by composing smaller components instead of inheriting one component from another component. Most of the components are user interface components. React app can include third party component for specific purpose such as routing, animation, state management, etc. Workflow of a React application Let us understand the workflow of a React application in this chapter by creating and analyzing a simple React application. Open a command prompt and go to your workspace. cd /go/to/your/workspace Next, create a folder, static_site and change directory to newly created folder. mkdir static_site cd static_site Example Next, create a file, hello.html and write a simple React application. <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>React Application</title> </head> <body> <div id=”react-app”></div> <script src=”https://unpkg.com/react@17/umd/react.development.js” crossorigin></script> <script src=”https://unpkg.com/react-dom@17/umd/react-dom.development.js” crossorigin></script> <script language=”JavaScript”> element = React.createElement(”h1”, {}, ”Hello React!”) ReactDOM.render(element, document.getElementById(”react-app”)); </script> </body> </html> Next, serve the application using serve web server. serve ./hello.html Output Next, open your favorite browser. Enter http://localhost:5000 in the address bar and then press enter. Let us analyse the code and do little modification to better understand the React application. Here, we are using two API provided by the React library. React.createElement Used to create React elements. It expects three parameters − Element tag Element attributes as object Element content – It can contain nested React element as well ReactDOM.render Used to render the element into the container. It expects two parameters − React Element OR JSX Root element of the webpage Nested React element As React.createElement allows nested React element, let us add nested element as shown below − Example <script language=”JavaScript”> element = React.createElement(”div”, {}, React.createElement(”h1”, {}, ”Hello React!”)); ReactDOM.render(element, document.getElementById(”react-app”)); </script> Output It will generate the below content − <div><h1> Hello React!</h1></div> Use JSX Next, let us remove the React element entirely and introduce JSX syntax as shown below − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>React Application</title> </head> <body> <div id=”react-app”></div> <script src=”https://unpkg.com/react@17/umd/react.development.js” crossorigin></script> <script src=”https://unpkg.com/react-dom@17/umd/react-dom.development.js” crossorigin></script> <script src=”https://unpkg.com/@babel/standalone/babel.min.js”></script> <script type=”text/babel”> ReactDOM.render( <div><h1>Hello React!</h1></div>, document.getElementById(”react-app”) ); </script> </body> </html> Here, we have included babel to convert JSX into JavaScript and added type=”text/babel” in the script tag. <script src=”https://unpkg.com/@babel/standalone/babel.min.js”></script> <script type=”text/babel”> … … </script> Next, run the application and open the browser. The output of the application is as follows − Next, let us create a new React component, Greeting and then try to use it in the webpage. <script type=”text/babel”> function Greeting() { return <div><h1>Hello JSX!</h1></div> } ReactDOM.render(<Greeting />, document.getElementById(”react-app”) ); </script> The result is same and as shown below − By analyzing the application, we can visualize the workflow of the React application as shown in the below diagram. React app calls ReactDOM.render method by passing the user interface created using React component (coded in either JSX or React element format) and the container to render the user interface. ReactDOM.render processes the JSX or React element and emits Virtual DOM. Virtual DOM will be merged and rendered into the container. Architecture of the React Application React library is just UI library and it does not enforce any particular pattern to write a complex application. Developers are free to choose