ReactJS – Managing State using Flux ”; Previous Next One of the important feature in a front-end application is state management. React has its own state management technique for its component. React state management works in the component level only. A component”s state will not be accessed in another component even through the components are in parent / child relationship (nested component). To overcome this problem, there are lot of third party state management libraries such as redux. mobx. etc., Flux is one of the technique to manage the state of the application effectively. Flux is introduced by Facebook and using it quite extensively in its web application. Flux uses a unidirectional data flow pattern to provide clear state management. Let us learn what is flux and how to use it in this chapter. Managing State using Flux Flux uses unidirectional data flow pattern. It has four distinct parts, Store − As the name implies, all business data are stored in the store. Store does two process. Store will update its data on its own by collecting the data from registered dispatcher. Dispatcher provides the store with data and related action. Once the data is updated, the store emit a change data event to inform the view that the data is changed. View will listen for change event and update its view upon receiving the change event by accessing the updated data from store. Action − Action are just the representation of the action to be processed with necessary data. View will create a action with necessary data based on the user interaction and send it to dispatcher. For example, the below mentioned payload is created by view (action creator) based on the user interaction to add a user. { actionType: “add”, data: { name: “Peter” } } Above mentioned action will be passed to dispatcher, which will send the information to all registered store. Store will update the data accordingly and send the change event to all view registered with it. Dispatcher − Dispatcher receives the actions with proper payload and sent it to all registered stores for further processing. View − View creates action based on the user interaction and send it to dispatcher. It registers with store to get the changes and once it receives the changes through events, it will update itself with new data. Few things needs to be initialized for the efficient working of the flux and are as follows − Dispatcher should be initialized by the application with proper actions and its callback. Store should be initialized and registered with the dispatcher to receive data updates. Views should be initialized with the dispatcher and store. Views should be registered to listen for store changes (events). The workflow of the flux architecture is as follows − User interact and fires an event in the view. View handles the event and creates an action based on the user”s action. View send the action to dispatcher. Dispatcher publish the action to all store registered with it, Registered store will receive the action with payload. Store will update itself based on the action. Store will emit change event to the view. View listening to store changes will update the front end with updated data. Applying flux Let us create a new react application to learn how to apply flux concept in this section. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, install flux package using npm as shown below − npm install flux –save Next, open App.css (src/App.css) and remove all CSS classes. Next, create a flux dispatcher, Dispatcher (src/Flux/Dispatcher.js) as shown below − import {Dispatcher} from “flux”; export default new Dispatcher(); Here, we have created a new dispatcher from the flux package. Next, create actions (and action creator), UserActions (src/Flux/UserActions.js) as shown below − import dispatcher from “./Dispatcher”; export const USER_ACTIONS = { ADD: ”addUser” }; export function addUser(userName) { dispatcher.dispatch({ type: USER_ACTIONS.ADD, value: { name: userName } }) } Here, USER_ACTIONS.ADD is a constant used to refer the user”s add action. addUser() is the method used to create action along with user data and dispatch the created action to dispatcher. Next, create a store, UserStore (src/Flux/UserStore.js) as shown below − import dispatcher from “./Dispatcher”; import {EventEmitter} from “events”; import * as UserActions from “./UserActions”; class UserStore extends EventEmitter { constructor() { super(); this.users = []; } handleActions(action) { switch (action.type) { case UserActions.USER_ACTIONS.ADD: { this.users.push(action.value); this.emit(“storeUpdated”); break; } default: { } } } getUsers() { return this.users; } } const userStore = new userStore(); dispatcher.register(userStore.handleActions.bind(userStore)); export default userStore; Here, UserStore is extended from EventEmitter to emit changes. handleActions retrieves the user details from dispatcher and update itself (this.users). handleActions emits the store update event to inform the views that the store is updated. getUsers() method will return the current user list information. Next, create a user input component, UserInput component to get the new user information as shown below − import React from “react”; import * as UserActions from “./UserActions”; export default class ButtonComponent extends React.Component { constructor(props) { super(props); this.state = { username: ”” } } onButtonClick = () => { UserActions.addUser(this.state.username) }; render() { return ( <div> <input name=”username” onChange={(e) => this.setState({username: e.target.value})}/> <button onClick={() => this.onButtonClick()}>Add user</button> </div> ); } } Here, Create a input element to get new user data from users. Added a button to submit user information to UserActions”s addUser() method addUser will update user data and send it to dispatcher with proper action type. Dispatcher will call store with action type. Store
Category: reactjs
ReactJS – Component Life Cycle Using React Hooks ”; Previous Next React Hooks provides a special Hook, useEffect() to execute certain functionality during the life cycle of the component. useEffect() combines componentDidMount, componentDidUpdate, and componentWillUnmount life cycle into a single api. The signature of the useEffect() api is as follows − useEffect( <executeFn>, <values> ); Here, executeFn − Function to execute when an effect occurs with an optional return function. The return function will be execute when a clean up is required (similar to componentWillUnmount). values − array of values the effect depends on. React Hooks execute the executeFn only when the values are changed. This will reduce unnecessary calling of the executeFn. Let us add useEffect() Hooks in our react-clock-hook-app application. Open react-clock-hook-app in your favorite editor. Next, open src/components/Clock.js file and start editing. Next, import useEffect api. import React, { useState, useEffect } from ”react”; Next, call useEffect with function to set date and time every second using setInterval and return a function to stop updating the date and time using clearInterval. useEffect( () => { let setTime = () => { console.log(“setTime is called”); setCurrentDateTime(new Date()); } let interval = setInterval(setTime, 1000); return () => { clearInterval(interval); } }, [] ); Here, Created a function, setTime to set the current time into the state of the component. Called the setInterval JavaScript api to execute setTime every second and stored the reference of the setInterval in the interval variable. Created a return function, which calls the clearInterval api to stop executing setTime every second by passing the interval reference. Now, we have updated the Clock component and the complete source code of the component is as follows − import React, { useState, useEffect } from ”react”; function Clock() { const [currentDateTime, setCurrentDateTime] = useState(new Date()); useEffect( () => { let setTime = () => { console.log(“setTime is called”); setCurrentDateTime(new Date()); } let interval = setInterval(setTime, 1000); return () => { clearInterval(interval); } }, [] ); return ( <div> <p>The current time is {currentDateTime.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); Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. The clock will be shown for 5 seconds and then, it will be removed from the DOM. By checking the console log, we can found that the cleanup code is properly executed. React children property aka Containment React allows arbitrary children user interface content to be included inside the component. The children of a component can be accessed through this.props.children. Adding children inside the component is called containment. Containment is used in situation where certain section of the component is dynamic in nature. For example, a rich text message box may not know its content until it is called. Let us create RichTextMessage component to showcase the feature of React children property in this chapter. First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create components folder under src folder. Next, create a file, RichTextMessage.js under src/components folder and start editing. Next, import React library. import React from ”react”; Next, create a class, RichTextMessage and call constructor with props. class RichTextMessage extends React.Component { constructor(props) { super(props); } } Next, add render() method and show the user interface of the component along with it”s children render() { return ( <div>{this.props.children}</div> ) } Here, props.children returns the children of the component. Wraped the children inside a div tag. Finally, export the component. export default RichTextMessage; The complete source code of the RichTextMessagecomponent is given below − import React from ”react”; class RichTextMessage extends React.Component { constructor(props) { super(props); } render() { return ( <div>{this.props.children}</div> ) } } export default RichTextMessage; Next, create a file, index.js under the src folder and use RichTextMessage component. import React from ”react”; import ReactDOM from ”react-dom”; import RichTextMessage from ”./components/RichTextMessage”; ReactDOM.render( <React.StrictMode> <RichTextMessage> <h1>Containment is really a cool feature.</h1> </RichTextMessage> </React.StrictMode>, document.getElementById(”root”) ); Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”utf-8″> <title>React App</title> </head> <body> <div id=”root”></div> <script type=”text/JavaScript” src=”./index.js”></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Browser emits component”s children wrapped in div tag as shown below − <div id=”root”> <div> <div> <h1>Containment is really a cool feature.</h1> </div> </div> </div> Next, change the child property of RichTextMessage component in index.js. import React from ”react”; import ReactDOM from ”react-dom”; import Clock from ”./components/Clock”; ReactDOM.render( <React.StrictMode> <RichTextMessage> <h1>Containment is really an excellent feature.</h1> </RichTextMessage> </React.StrictMode>, document.getElementById(”root”) ); Now, browser updates the component”s children content and emits as shown below − <div id=”root”> <div> <div> <h1>Containment is really an excellent feature.</h1> </div> </div> </div> In short, containment is an excellent feature to pass arbitrary user interface content to the component.
ReactJS – Styling
ReactJS – Styling ”; Previous Next In general, React allows component to be styled using CSS class through className attribute. Since, the React JSX supports JavaScript expression, a lot of common CSS methodology can be used. Some of the top options are as follows − CSS stylesheet − Normal CSS styles along with className Inline styling − CSS styles as JavaScript objects along with camelCase properties. CSS Modules − Locally scoped CSS styles. Styled component − Component level styles. Sass stylesheet − Supports Sass based CSS styles by converting the styles to normal css at build time. Post processing stylesheet − Supports Post processing styles by converting the styles to normal css at build time. Let use learn how to apply the three important methodology to style our component in this chapter. CSS Stylesheet Inline Styling CSS Modules CSS Stylesheet CSS stylesheet is usual, common and time-tested methodology. Simply create a CSS stylesheet for a component and enter all your styles for that particular component. Then, in the component, use className to refer the styles. Let us style our ExpenseEntryItem component. Open expense-manager application in your favorite editor. Next, open ExpenseEntryItem.css file and add few styles. div.itemStyle { color: brown; font-size: 14px; } Next, open ExpenseEntryItem.js and add className to the main container. import React from ”react”; import ”./ExpenseEntryItem.css”; class ExpenseEntryItem extends React.Component { render() { return ( <div className=”itemStyle”> <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; Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. CSS stylesheet is easy to understand and use. But, when the project size increases, CSS styles will also increase and ultimately create lot of conflict in the class name. Moreover, loading the CSS file directly is only supported in Webpack bundler and it may not supported in other tools. Inline Styling Inline Styling is one of the safest ways to style the React component. It declares all the styles as JavaScript objects using DOM based css properties and set it to the component through style attributes. Let us add inline styling in our component. Open expense-manager application in your favorite editor and modify ExpenseEntryItem.js file in the src folder. Declare a variable of type object and set the styles. itemStyle = { color: ”brown”, fontSize: ”14px” } Here, fontSize represent the css property, font-size. All css properties can be used by representing it in camelCase format. Next, set itemStyle style in the component using curly braces {} − render() { return ( <div style={ this.itemStyle }> <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> ); } Also, style can be directly set inside the component − render() { return ( <div style={ { color: ”brown”, fontSize: ”14px” } }> <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> ); } Now, we have successfully used the inline styling in our application. Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. CSS Modules Css Modules provides safest as well as easiest way to define the style. It uses normal css stylesheet with normal syntax. While importing the styles, CSS modules converts all the styles into locally scoped styles so that the name conflicts will not happen. Let us change our component to use CSS modules Open expense-manager application in your favorite editor. Next, create a new stylesheet, ExpenseEntryItem.module.css file under src/components folder and write regular css styles. div.itemStyle { color: ”brown”; font-size: 14px; } Here, file naming convention is very important. React toolchain will pre-process the css files ending with .module.css through CSS Module. Otherwise, it will be considered as a normal stylesheet. Next, open ExpenseEntryItem.js file in the src/component folder and import the styles. import styles from ”./ExpenseEntryItem.module.css” Next, use the styles as JavaScript expression in the component. <div className={styles.itemStyle}> Now, we have successfully used the CSS modules in our application. The final and complete code is − import React from ”react”; import ”./ExpenseEntryItem.css”; import styles from ”./ExpenseEntryItem.module.css” class ExpenseEntryItem extends React.Component { render() { return ( <div className={styles.itemStyle} > <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; Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Print Page Previous Next Advertisements ”;
ReactJS – Uncontrolled Component ”; Previous Next As we learned earlier, uncontrolled component does not support React based form programming. Getting a value of a React DOM element (form element) is not possible without using React api. One way to get the content of the react component is using React ref feature. React provides a ref attribute for all its DOM element and a corresponding api, React.createRef() to create a new reference (this.ref). The newly created reference can be attached to the form element and the attached form element”s value can be accessed using this.ref.current.value whenever necessary (during validation and submission). Form programming in uncontrolled component Let us see the step by step process to do form programming in uncontrolled component. Step 1 − Create a reference. this.inputRef = React.createRef(); Step 2 − Create a form element. <input type=”text” name=”username” /> Step 3 − Attach the already created reference in the form element. <input type=”text” name=”username” ref={this.inputRef} /> To set defalut value of an input element, use defaultValue attribute instead of value attribute. If value is used, it will get updated during rendering phase of the component. <input type=”text” name=”username” ref={this.inputRef} defaultValue=”default value” /> Finally, get the input value using this.inputRef.current.value during validation and submission. handleSubmit(e) { e.preventDefault(); alert(this.inputRef.current.value); } Creating Simple Form Let us create a simple form to add expense entry using uncontrolled component in this chapter. Step 1 − First, create a new react application, react-form-uncontrolled-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Step 2 − Open the application in your favorite editor. Create src folder under the root directory of the application. Create components folder under src folder. Step 3 − Create a file, ExpenseForm.css under src folder to style the component. input[type=text], input[type=number], input[type=date], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } input[type=submit] { width: 100%; background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; } input[type=submit]:hover { background-color: #45a049; } input:focus { border: 1px solid #d9d5e0; } #expenseForm div { border-radius: 5px; background-color: #f2f2f2; padding: 20px; } Step 4 − Create a file, ExpenseForm.js under src/components folder and start editing. Step 5 − Import React library. import React from ”react”; Import ExpenseForm.css file. import ”./ExpenseForm.css” Create a class, ExpenseForm and call constructor with props. class ExpenseForm extends React.Component { constructor(props) { super(props); } } Create React reference for all input fields. this.nameInputRef = React.createRef(); this.amountInputRef = React.createRef(); this.dateInputRef = React.createRef(); this.categoryInputRef = React.createRef(); Create render() method and add a form with input fields to add expense items. render() { return ( <div id=”expenseForm”> <form> <label for=”name”>Title</label> <input type=”text” id=”name” name=”name” placeholder=”Enter expense title” /> <label for=”amount”>Amount</label> <input type=”number” id=”amount” name=”amount” placeholder=”Enter expense amount” /> <label for=”date”>Spend Date</label> <input type=”date” id=”date” name=”date” placeholder=”Enter date” /> <label for=”category”>Category</label> <select id=”category” name=”category” > <option value=””>Select</option> <option value=”Food”>Food</option> <option value=”Entertainment”>Entertainment</option> <option value=”Academic”>Academic</option> </select> <input type=”submit” value=”Submit” /> </form> </div> ) } Add an event handler for the submit action. onSubmit = (e) => { e.preventDefault(); let item = {}; item.name = this.nameInputRef.current.value; item.amount = this.amountInputRef.current.value; item.date = this.dateInputRef.current.value; item.category = this.categoryInputRef.current.value; alert(JSON.stringify(item)); } Attach the event handlers to the form. render() { return ( <div id=”expenseForm”> <form onSubmit={(e) => this.onSubmit(e)}> <label for=”name”>Title</label> <input type=”text” id=”name” name=”name” placeholder=”Enter expense title” ref={this.nameInputRef} /> <label for=”amount”>Amount</label> <input type=”number” id=”amount” name=”amount” placeholder=”Enter expense amount” ref={this.amountInputRef} /> <label for=”date”>Spend Date</label> <input type=”date” id=”date” name=”date” placeholder=”Enter date” ref={this.dateInputRef} /> <label for=”category”>Category</label> <select id=”category” name=”category” ref={this.categoryInputRef} > <option value=””>Select</option> <option value=”Food”>Food</option> <option value=”Entertainment”>Entertainment</option> <option value=”Academic”>Academic</option> </select> <input type=”submit” value=”Submit” /> </form> </div> ) } Finally, export the component. export default ExpenseForm The complete code of the ExpenseForm component is given below import React from ”react”; import ”./ExpenseForm.css” class ExpenseForm extends React.Component { constructor(props) { super(props); this.nameInputRef = React.createRef(); this.amountInputRef = React.createRef(); this.dateInputRef = React.createRef(); this.categoryInputRef = React.createRef(); } onSubmit = (e) => { e.preventDefault(); let item = {}; item.name = this.nameInputRef.current.value; item.amount = this.amountInputRef.current.value; item.date = this.dateInputRef.current.value; item.category = this.categoryInputRef.current.value; alert(JSON.stringify(item)); } render() { return ( <div id=”expenseForm”> <form onSubmit={(e) => this.onSubmit(e)}> <label for=”name”>Title</label> <input type=”text” id=”name” name=”name” placeholder=”Enter expense title” ref={this.nameInputRef} /> <label for=”amount”>Amount</label> <input type=”number” id=”amount” name=”amount” placeholder=”Enter expense amount” ref={this.amountInputRef} /> <label for=”date”>Spend Date</label> <input type=”date” id=”date” name=”date” placeholder=”Enter date” ref={this.dateInputRef} /> <label for=”category”>Category</label> <select id=”category” name=”category” ref={this.categoryInputRef} > <option value=””>Select</option> <option value=”Food”>Food</option> <option value=”Entertainment”>Entertainment</option> <option value=”Academic”>Academic</option> </select> <input type=”submit” value=”Submit” /> </form> </div> ) } } export default ExpenseForm; index.js Next, create a file, index.js under the src folder and use ExpenseForm component. import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseForm from ”./components/ExpenseForm” ReactDOM.render( <React.StrictMode> <ExpenseForm /> </React.StrictMode>, document.getElementById(”root”) ); index.html Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”utf-8″> <title>React App</title> </head> <body> <div id=”root”></div> <script type=”text/JavaScript” src=”./index.js”></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Finally, enter a sample expense detail and click submit. The submitted data will be collected and showed in a pop-up message box. Print Page Previous Next Advertisements ”;
ReactJS – Testing
ReactJS – Testing ”; Previous Next Testing is one of the processes to make sure that the functionality created in any application is working in accordance with the business logic and coding specification. React recommends React testing library to test React components and jest test runner to run the test. The react-testing-library allows the components to be checked in isolation. It can be installed in the application using below command − npm install –save @testing-library/react @testing-library/jest-dom Create React app Create React app configures React testing library and jest test runner by default. So, testing a React application created using Create React App is just a command away. cd /go/to/react/application npm test The npm test command is similar to npm build command. Both re-compiles as and when the developer changes the code. Once the command is executed in the command prompt, it emits below questions. No tests found related to files changed since last commit. Press `a` to run all tests, or run Jest with `–watchAll`. Watch Usage › Press a to run all tests. › Press f to run only failed tests. › Press q to quit watch mode. › Press p to filter by a filename regex pattern. › Press t to filter by a test name regex pattern. › Press Enter to trigger a test run. Pressing a will try to run all the test script and finally summaries the result as shown below − Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 4.312 s, estimated 12 s Ran all test suites. Watch Usage: Press w to show more. Testing in a custom application Let us write a custom React application using Rollup bundler and test it using React testing library and jest test runner in this chapter. First, create a new react application, react-test-app using Rollup bundler by following instruction in Creating a React application chapter. Next, install the testing library. cd /go/to/react-test-app npm install –save @testing-library/react @testing-library/jest-dom Next, open the application in your favorite editor. Next, create a file, HelloWorld.test.js under src/components folder to write test for HelloWorld component and start editing. Next, import react library. import React from ”react”; Next, import the testing library. import { render, screen } from ”@testing-library/react”; import ”@testing-library/jest-dom”; Next, import our HelloWorld component. import HelloWorld from ”./HelloWorld”; Next, write a test to check the existence of Hello World text in the document. test(”test scenario 1”, () => { render(<HelloWorld />); const element = screen.getByText(/Hello World/i); expect(element).toBeInTheDocument(); }); The complete source code of the test code is given below − import React from ”react”; import { render, screen } from ”@testing-library/react”; import ”@testing-library/jest-dom”; import HelloWorld from ”./HelloWorld”; test(”test scenario 1”, () => { render(<HelloWorld />); const element = screen.getByText(/Hello World/i); expect(element).toBeInTheDocument(); }); Next, install jest test runner, if it is not installed already in the system. npm install jest -g Next, run jest command in the root folder of the application. jest Next, run jest command in the root folder of the application. PASS src/components/HelloWorld.test.js √ test scenario 1 (29 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 5.148 s Ran all test suites. Print Page Previous Next Advertisements ”;
ReactJS – Component Collection ”; Previous Next In modern application, developer encounters a lot of situations, where list of item (e.g. todos, orders, invoices, etc.,) has to be rendered in tabular format or gallery format. React provides clear, intuitive and easy technique to create list based user interface. React uses two existing features to accomplish this feature. JavaScript”s built-in map method. React expression in jsx. Map Method The map function accepts a collection and a mapping function. The map function will be applied to each and every item in the collection and the results are used to generate a new list. For instance, declare a JavaScript array with 5 random numbers as shown below − let list = [10, 30, 45, 12, 24] Now, apply an anonymous function, which double its input as shown below − result = list.map((input) => input * 2); Then, the resulting list is − [20, 60, 90, 24, 48] To refresh the React expression, let us create a new variable and assign a React element. var hello = <h1>Hello!</h1> var final = <div>{helloElement}</div> Now, the React expression, hello will get merged with final and generate, <div><h1>Hello!</h1></div> Example Let us apply this concept to create a component to show a collection of expense entry items in a tabular format. Step 1 − Open our expense-manager application in your favorite editor. Create a file ExpenseEntryItemList.css in src/components folder to include styles for the component. Create another file, ExpenseEntryItemList.js in src/components folder to create ExpenseEntryItemList component Step 2 − Import React library and the stylesheet. import React from ”react”; import ”./ExpenseEntryItemList.css”; Step 3 − Create ExpenseEntryItemList class and call constructor function. class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } } Create a render() function. render() { } Step 4 − Use the map method to generate a collection of HTML table rows each representing a single expense entry item in the list. render() { const lists = this.props.items.map( (item) => <tr key={item.id}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> </tr> ); } Here, key identifies each row and it has to be unique among the list. Step 5 − Next, in the render() method, create a HTML table and include the lists expression in the rows section. return ( <table> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> </tr> </thead> <tbody> {lists} </tbody> </table> ); Finally, export the component. export default ExpenseEntryItemList; Now, we have successfully created the component to render the expense items into HTML table. The complete code is as follows − import React from ”react”; import ”./ExpenseEntryItemList.css” class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } render() { const lists = this.props.items.map( (item) => <tr key={item.id}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> </tr> ); return ( <table> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> </tr> </thead> <tbody> {lists} </tbody> </table> ); } } export default ExpenseEntryItemList; index.js: Open index.js and import our newly created ExpenseEntryItemList component. import ExpenseEntryItemList from ”./components/ExpenseEntryItemList” Next, 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: “2020-11-02”, category: “Gadgets” }, { id: 1, name: “Exam Fees”, amount: 1245, spendDate: “2020-11-04”, category: “Academic” } ] ReactDOM.render( <React.StrictMode> <ExpenseEntryItem item={item} /> </React.StrictMode>, document.getElementById(”root”) ); ExpenseEntryItemList.css: Open ExpenseEntryItemList.css and add style for the table. html { font-family: sans-serif; } table { border-collapse: collapse; border: 2px solid rgb(200,200,200); letter-spacing: 1px; font-size: 0.8rem; } td, th { border: 1px solid rgb(190,190,190); padding: 10px 20px; } th { background-color: rgb(235,235,235); } td, th { text-align: left; } tr:nth-child(even) td { background-color: rgb(250,250,250); } tr:nth-child(odd) td { background-color: rgb(245,245,245); } caption { padding: 10px; } Start the application using npm command. npm start Output Finally, open the browser and enter http://localhost:3000 in the address bar and press enter. Item Amount Date Category Pizza 80 Sat
ReactJS – Advantages & Disadvantages ”; Previous Next React is a library for building composable user interfaces. It encourages the creation of reusable UI components, which present data that changes over time. Lots of people use React as the V in MVC. React abstracts away the DOM from you, offering a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native. React implements one-way reactive data flow, which reduces the boilerplate and is easier to reason about than traditional data binding. Advantages of ReactJS Following are the main advantages of ReactJS − Performance Easy to learn Huge collection of third party components Large community SEO Friendliness Easy kick-starting of the React project Rich set of developer tools Handle large application Performance React uses Virtual DOM concept to check and update the HTML document. Virtual DOM is a special DOM created by React. Virtual DOM represents the real DOM of the current document. Whenever there is a change in the 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. Easy to learn The core concept of React can be learned in less than a day. React can be coded in either Plain Javascript (ES6) or Typescript. To start with React, the basic knowledge of the JavaScript is enough. For advanced developer, Typescript provides type safety and rich language feature. A react component can be created by a developer in few hours by learning JSX (similar to HTML) and properties (props). Learning React state management will enable the developer to create dynamic component, which updates the content whenever the state changes. React provides simple lifecycle for its component, which can be used to properly setup and destroy the component. Huge collection of third party components In addition to core react library (which is only a few KB in size), React community provides a large number of component for a wide range of application from simple UI component to full fledged PDF Viewer component. React provides multiple option in each category. For example, the advanced state management can be done using either Redux or MobX library. Redux and Mobx are just two popular library to do state management. React has more than 10 library to archive the same functionality. Similarly, React community provides lot of third party library in each category like routing, data grid, calendar, form programming, etc., Large community React developer community is a huge community with lot of activities. React community is very active that you can get answer for any react related question / doubts in a few minutes through google, stackoverflow, etc., SEO friendliness React is one of the few JavaScript library to support SEO features. Since React components and JSX are similar to HTML elements, SEO can be easily achieved without much code / setup. Easy kickstart of React project React provides a CLI application, create-react-app to create a new react application. create-react-app application not only create a new application, it also build and run the application in the local environment without any other dependencies. create-react-app allows the developer to choose a template, which allows the application to include more boilerplate code during initial setup itself. This allows the developer to kickstart small application to large application in few clicks. In addition to create-react-app, React community additional tools such as nextjs, gatsby, etc., which allows developer to create advanced application in a short period of time. Rich set of developer tools React community provides essential developer tools to enhance the developer productivity. React developer tool for chrome, edge and firefox browser enables developer to select a react component and see the current state of the component. Also, it enables the developer to has clear picture of the view of the component hierarchy by show it as a tree of component in the Developer Tab of the browser. Handle large application React uses composition to merge multiple component into one bigger component, which in turn allows to create much more larger component. React component can be created in a single JavaScript file and can be set as exportable. This feature allows multiple component to be grouped under a common category as module and can be reused in other places. Composable and modular features of the React library allows developer to create large application, which is relatively easy to maintain when compared to other front end framework. Disadvantages of React Even through React library has lot of positives, it has some of the drawbacks as well. Some of the drawbacks are as follows − Lack of quality documentation No standard / recommended way to develop application Fast development pace Advanced use of JavaScript JavaScript extension Just a UI library Lack of quality documentation React library has a decent documentation in its primary website. It covers the basic concept with few examples. Even though, it is a good start to understand the basic of React concept, it does not provides a deep and detailed explanation with multiple examples. React community steps in and provides lot of articles with varying level of complexity and quality. But, they are not organized under one place, where the developer can easily learn. No or Less standard way to develop application React is just a UI library with few concept and standard
ReactJS – Home
ReactJS Tutorial Table of content What is ReactJS? Who should learn ReactJS? Why Learn ReactJS? ReactJS Example Code Features of ReactJS Prerequisites to Learn ReactJS Getting Started with ReactJS Frequently Asked Questions on ReactJS Job Search PDF Version Quick Guide Resources Discussion This ReactJS tutorial includes all of the most recent updates up to version 18.2.0 and covers every topic, from fundamental to advanced. React is the most recommended JavScript library to learn now because of its core foundation of features and large community. What is ReactJS? ReactJS is an open-source JavaScript library for building dynamic and interactive user interfaces(UIs). React is developed and released by Facebook. Facebook is continuously working on the React library and enhancing it by fixing bugs and introducing new features. Who should learn ReactJS? This tutorial is prepared for beginners to working professionals who are aspiring to make a career in the field of developing front-end web applications. This tutorial is intended to make you comfortable in getting started with the React concepts with examples. Why Learn ReactJS? There are several reasons to learn ReactJS, as per the demand in the development industry of React developers and features React has to offer that can not be replaced by other frameworks or libraries. Ease of Use: ReactJS does not require writing lengthy codes as it supports the Components concept so a small amount of code can be created and can be used in multiple places. Multiple Module Support: There are so many modules in ReactJS that can be used to make your development more scalable, and manageable at a fast pace. Multiple Apps Development: By using React knowledge we can create Web Pages, Web Apps, Mobile Apps, and VR Apps. There are a lot of websites that are using ReactJS like Airbnb, Cloudflare, Facebook, Instagram, etc. Easy Migration: Because of its easy learning curve migration from other technologies became so easy. There are tons of resources to learn ReactJS from basics to advanced. Large Community: ReactJS has one of the largest communities to help you when you are in trouble debugging your codes or get stuck learning new things. ReactJS Example Code As this is sample code without the environment setup this code will not work to set up the ReactJS environment check ReactJS Installation article. import React from ”react”; import ReactDOM from ”react-dom/client”; function Greeting(props) { return <h1>Welcome to TutorialsPoint</h1>; } const container = document.getElementById(“root”); const root = ReactDOM.createRoot(container); root.render(<Greeting />); Features of ReactJS ReactJS plays an essential role in the front-end ecosystem. There are so many important features of ReactJS as it is the most demanding library for front-end development. Virtual DOM: Virtual DOM is a special kind of DOM that is used in ReactJS. 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 updates only the difference in th actual/real DOM. Reusable Components: Components need to be written a single time and can be used multiple times by just calling that component where we require that component. One-Way Data Binding: One-way data binding prevents the data in a component from flowing backward. A component can pass the data to its child component only. This will simplify the data handling and reduce the complexity. To know more about the features of ReactJS please check ReactJS Features article. Prerequisites to Learn ReactJS Before proceeding with this tutorial, we assume that the readers have the basic knowledge in HTML, CSS and JavaScript concepts. Getting Started with ReactJS To get started with ReactJS we need to clear our fundamentals first before proceeding into complex topics. We will recommend you to code along with each article you read this will help you to understand the concepts. If you can create a project along with your learning that will be more helpful. Basics of ReactJS ReactJS Introduction ReactJS Installation ReactJS Features ReactJS Architecture ReactJS JSX ReactJS Application ReactJS Fragments ReactJS Conditional Rendering ReactJS CLI Commands ReactJS Components Component is the heart of ReactJS, it is the building block of a React application. A React component represents a small chunk of user interface in a webpage. Components ReactJS – Use Component ReactJS Nested Components ReactJS Component Collection ReactJS Component Using Properties ReactJS Component Life Cycle ReactJS Event-Aware Component ReactJS Stateless Component ReactJS Layout Component ReactJS States State represents the value of the dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. ReactJS State Management ReactJS State Management API ReactJS – State Management through Hooks ReactJS Hooks Hooks are plain JavaScript functions having access to state and lifecycle events of the component in which it is used. In general, hooks start with the use keyword. ReactJS Introduction to Hooks ReactJS useState Hook ReactJS useEffect Hook ReactJS useContext Hook ReactJS useRef Hook ReactJS useReducer Hook ReactJS useCallback Hook ReactJS useMemo Hook ReactJS Custom Hooks ReactJS Props Props are used to pass data between components. In real-world projects we need the components to interact with each other which is not possible with the states as it is private to that particular component. ReactJS Props ReactJS Props Validation Other Important Topics
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: