ReactJS – Formik

ReactJS – Formik ”; Previous Next Formik is third party React form library. It provides basic form programming and validation. It is based on controlled component and greatly reduces the time to do form programming. 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. Expense Form Using Formik In this chapter, let us recreate the expense form using Formik library. Step 1 − First, create a new react application, react-formik-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Step 2 − Install the Formik library. cd /go/to/workspace npm install formik –save Step 3 − Open the application in your favorite editor. Create src folder under the root directory of the application. Create components folder under src folder. Step 4 − 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; } #expenseForm span { color: red; } Step 5 − Create another file, ExpenseForm.js under src/components folder and start editing. Import React and Formik library. import React from ”react”; import { Formik } from ”formik”; Next, import ExpenseForm.css file. import ”./ExpenseForm.css” Next, create ExpenseForm class. class ExpenseForm extends React.Component { constructor(props) { super(props); } } Set initial values of the expense item in the constructor. this.initialValues = { name: ””, amount: ””, date: ””, category: ”” } Next, create a validation method. Formik will send the current values entered by the user. validate = (values) => { const errors = {}; if (!values.name) { errors.name = ”Required”; } if (!values.amount) { errors.amount = ”Required”; } if (!values.date) { errors.date = ”Required”; } if (!values.category) { errors.category = ”Required”; } return errors; } Create a method to submit the form. Formik will send the current values entered by the user. handleSubmit = (values, setSubmitting) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); setSubmitting(false); }, 400); } Create render() method. Use handleChange, handleBlur and handleSubmit method provided by Formik as input elements event handler. render() { return ( <div id=”expenseForm”> <Formik initialValues={this.initialValues} validate={values => this.validate(values)} onSubmit={(values, { setSubmitting }) => this.handleSubmit(values, setSubmitting)} >{ ({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, /* and other goodies */ }) => ( <form onSubmit={handleSubmit}> <label for=”name”>Title <span>{errors.name && touched.name && errors.name}</span></label> <input type=”text” id=”name” name=”name” placeholder=”Enter expense title” onChange={handleChange} onBlur={handleBlur} value={values.name} /> <label for=”amount”>Amount <span>{errors.amount && touched.amount && errors.amount}</span></label> <input type=”number” id=”amount” name=”amount” placeholder=”Enter expense amount” onChange={handleChange} onBlur={handleBlur} value={values.amount} /> <label for=”date”>Spend Date <span>{errors.date && touched.date && errors.date}</span></label> <input type=”date” id=”date” name=”date” placeholder=”Enter date” onChange={handleChange} onBlur={handleBlur} value={values.date} /> <label for=”category”>Category <span>{errors.category && touched.category && errors.category}</span></label> <select id=”category” name=”category” onChange={handleChange} onBlur={handleBlur} value={values.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” disabled={isSubmitting} /> </form> ) } </Formik> </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” import { Formik } from ”formik”; class ExpenseFormik extends React.Component { constructor(props) { super(props); this.initialValues = { name: ””, amount: ””, date: ””, category: ”” } } validate = (values) => { const errors = {}; if (!values.name) { errors.name = ”Required”; } if (!values.amount) { errors.amount = ”Required”; } if (!values.date) { errors.date = ”Required”; } if (!values.category) { errors.category = ”Required”; } return errors; } handleSubmit = (values, setSubmitting) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); setSubmitting(false); }, 400); } render() { return ( <div id=”expenseForm”> <Formik initialValues={this.initialValues} validate={values => this.validate(values)} onSubmit={(values, { setSubmitting }) => this.handleSubmit(values, setSubmitting)} > { ({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, /* and other goodies */ }) => ( <form onSubmit={handleSubmit}> <label for=”name”>Title <span>{errors.name && touched.name && errors.name}</span></label> <input type=”text” id=”name” name=”name” placeholder=”Enter expense title” onChange={handleChange} onBlur={handleBlur} value={values.name} /> <label for=”amount”>Amount <span>{errors.amount && touched.amount && errors.amount}</span></label> <input type=”number” id=”amount” name=”amount” placeholder=”Enter expense amount” onChange={handleChange} onBlur={handleBlur} value={values.amount} /> <label for=”date”>Spend Date <span>{errors.date && touched.date && errors.date}</span></label> <input type=”date” id=”date” name=”date” placeholder=”Enter date” onChange={handleChange} onBlur={handleBlur} value={values.date} /> <label for=”category”>Category <span>{errors.category && touched.category && errors.category}</span></label> <select id=”category” name=”category” onChange={handleChange} onBlur={handleBlur} value={values.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” disabled={isSubmitting} /> </form> ) } </Formik> </div> ) } } export default ExpenseForm; index.js 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> Serve the application using npm command. npm start 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 popup message box. The interactive version of the

ReactJS – Keys

ReactJS – Keys ”; Previous Next List and keys We learned how to use collections in React using for loop and map function in previous chapters. If we run the application, it output as expected. If we open the developer console in the browser, then it will show a warning as shown below − Warning: Each child in a list should have a unique “key” prop. Check the render method of `ExpenseListUsingForLoop`. See https://reactjs.org/link/warning-keys for more information. tr ExpenseListUsingForLoop@ div App So, what does it means and how it affects our React application. As we know, React tries to render only the updated values in DOM through various mechanism. When the React renders a collection, it tries to optimize the rendering by updating only the updated item in the list. But, there is no hint for the React to find which items are new, updated or removed. To get the information, React allows a key attributes for all components. The only requirement is that the value of the key should be unique among the current collection. Let us recreate one of our earlier application and apply the key attributes. 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. Then, 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 = [] expenses = items.map((item, idx) => <tr key={idx}><td>item {idx + 1}</td><td>{item}</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 map function, created table row (tr) for each entry using transform function and finally set the returned array in expenses variable. Set the key attributes for each row with the index value of the item. Used expenses array in the JSX expression to include the generated rows. Used 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 = [] expenses = items.map( (item, idx) => <tr key={idx}><td>item {idx + 1}</td><td>{item}</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; } Next, check the application in the browser. It will show the expenses as shown below − Finally, open the developer console and find that the warning about key is not shown. Key and index We learned that the key should be unique to optimize the rendering of the component. We used index value and the error is gone. Is it still correct way to provide value for the list? The answer is Yes and No. Setting the index key will work in most situation but it will behave in unexpected ways if we use uncontrolled component in our application. Let us update our application and add two new features as specified below − Add an input element to each row adjacent to expense amount. Add a button to remove the first element in the list. First of all, add a constructor and set the initial state of the application. As we are going to remove certain item during runtime of our application, we should use state instead of props. constructor(props) { super(props) this.state = { expenses: this.props[”expenses”] } } Next, add a function to remove the first element of the list. remove() { var itemToRemove = this.state[”expenses”][0] this.setState((previousState) => ({ expenses: previousState[”expenses”].filter((item) => item != itemToRemove) })) } Next, bind the remove function in the constructor as shown below − constructor(props) { super(props) this.state = { expenses: this.props[”expenses”] } this.remove = this.remove.bind(this) } Next, add a button below the table and set remove function in its onClick action. render() { var items = this.state[”expenses”]; var expenses = [] expenses = items.map( (item, idx) => <tr key={idx}><td>item {idx + 1}</td><td>{item}</td></tr>) var total = this.getTotalExpenses(); return ( <div> <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> <div> <button onClick={this.remove}>Remove first item</button> </div> </div>

ReactJS – Strict Mode

ReactJS – Strict Mode ”; Previous Next React is build on the concept of component, properties and state. React provides a relatively few set of API to create and update components. The basic features of React is enough for large part of the our front end application. But, still modern application has complex scenarios, which needs advanced front-end logic. React provides lot of high-level API, which will help us to create complex front-end application. The high-level API comes with a cost. High-level API are little bit tough to learn and apply it in our application. React provides a strict mode, which helps the developer to properly apply the high-level API by highlighting the potential problem during development phase of our application. As we know, everything in the React is build on the concept of components, strict mode is simply a non-visual component, React.StrictMode. The usage of strict mode component is also very simple. Just wrap the component to be analyzed with React.StrictMode component as shown below − <React.StrictMode> <OurComplexComponent /> </React.StrictMode> Another functionality of the strict mode is to throw error or warning when certain legacy or depreciated API (which will eventually introduce bugs in the application) are used in the application. Let us learn the list of items highlighted by strict mode component in this chapter. Unsafe lifecycle usage React identifies some of the legacy lifecycle events are unsafe to use in the async based application. They are as follows − componentWillMount componentWillReceiveProps componentWillUpdate Unsafe means it will create hard to debug bugs in the application. React will eventually remove these unsafe lifecycle event in the future version of the library. Until then, developer are alerted when they use legacy unsafe lifecycle events. Legacy ref API usage Earlier version of React uses string based ref management and later added callback based ref management. The recommended way is to use callback based option due to its stability and less error-prone nature. Strict mode will throw warning if we use string based option. The most recent version of React provides improved ref management option, which is both easy to code and less error-prone nature. Legacy findDOMNode usage findDOMNode helps to search the tree of DOM node given a class instance. The usage of findDOMNode is depreciated and promotes the usage of ref based DOM management. Side effects React has two major phases, render and commit. render phase involves major work and time-consuming and commit phase is straight forward and fast. React introduces a concurrent mode, which will improve the performance of the render phase. One of the requirement of the concurrent mode is that the lifecycle event used in the render phase should not contain side effects. React will try to find the unexpected side effects using different approaches during development phase and report it as warning. Legacy context API Legacy context API is error-prone and it is not recommended to use. It will be removed in the future version. Until then, strict mode will detect the usage of legacy context API and report it. Reusable state Components with reusable state can be mounted and destroyed multiple time without any side effects and will help to improve the performance of the application. The future version of the React library will add or remove section of UI while preserving state. React 18 introduces a strict mode feature, which will try to unmount and remount the component to ensure the component is resilient. Any issue during this phase will be reported. Print Page Previous Next Advertisements ”;

ReactJS – Inline Style

ReactJS – Inline Style ”; Previous Next React provides a unique way of directly writing the CSS in the react component and using it inside JSX. The concept is called CSS in JS and provides many advantages over traditional usage of styles. Let us learn what is inline styling and how to use it react component. Concept of inline styling CSS enables the developer to design the UI of the web application. React provides first class support for CSS and allows CSS to be imported directly into the react application. Directly importing CSS into a react component is as simple as importing a package. import ”./App.css” But, importing css directly into the web component has one major disadvantage, Global namespace. Global style may affect the style of an individual component if there is a conflict in the class name. Developer need to be careful to assign some prefix to make sure that the conflict will not happen. The other way around is to allow the Javascript to manage the CSS and it is called CSS in JS. React allows the CSS to be used inside the JSX through special CSS syntax. React provides a style props for every component, which can be used specify inline style. The inline style should be provided in a Javascript object. The object should follows the below mentioned rules, The object key should be CamelCased version of normal CSS attributes. For example, the background-color should be specified as backgroundColor. { backgroundColor: “red” } The object value should be one of the allowed values of the corresponding object key in CSS and should be in string format. For example, the font-size CSS attributes and its value (12px) should be specified as follows − { fontSize: “12px” } React will handle the conflict and render the application correctly. Applying inline style Let us learn how to apply inline style in a react application in this section. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, open App.css (src/App.css) and remove all the CSS classes. // remove the css Next, create a simple component, SimpleStyle (src/Components/SimpleIcon.js) as shown below − import React from “react”; class SimpleStyle extends React.Component { displayStyle = { fontFamily: ”Times New Roman”, fontSize: “24px”, color: “red” } render() { return ( <div> <div style={this.displayStyle}> Sample text to understand inline style (object as variable) in React component </div> <hr /> <div style={{ fontFamily: ”Arial”, fontSize: “24px”, color: “grey”}}> Sample text to understand inline style (object as expression) in React component </div> </div> ) } } export default SimpleStyle Here we have, Styled the first div using variable (displayStyle). Styled the second div using expression. Next, open App component (src/App.js) and update the content with SimpleStyle component as shown below − import ”./App.css” import React from ”react”; import SimpleStyle from ”./Components/SimpleStyle” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleStyle /> </div> </div> </div> ); } export default App; Here we have, Imported the SimpleStyle component. Used SimpleStyle component to render the calender icon. Finally, open the application in the browser. The content will be rendered as shown below − Summary Inline styling helps developer to quickly include the CSS style without worrying about the conflict of the CSS styles. Also, the syntax is very similar to CSS and it makes it easy for the developer to use the feature without much learning curve. Print Page Previous Next Advertisements ”;

ReactJS – Pagination

ReactJS – Pagination ”; Previous Next React provides pagination component through third party UI component library. React community provides a large collection of UI / UX components and it is tough to choose the right library for our requirement. Bootstrap UI library is one of the popular choice for the developer and it is extensively used. React Bootstrap (https://react-bootstrap.github.io/) has ported almost all the bootstrap UI components and it has best support for Pagination component as well. Let us learn how to use Pagination component from react-bootstrap library in this chapter. Pagination component Pagination component allows the developer to create simple pagination with bootstrap design in a web application. Pagination component accepts below components. Pagination.Item Pagination.First Pagination.Last Pagination.Previous Pagination.Next Pagination component accepts a small set of props to customize the pagination component and they are as follows − size (sm | lg) Set the size of the pagination buttons bsPrefix (string) Enables to change the underlying component CSS Pagination.Item component accepts a small set of props to customize the pagination component and they are as follows − active (boolean) Set the item as active one and don”t render a tag. activeLabel (string) Label to indicate the state of the pagination item disabled (boolean) Disable the pagination item href (string) Link for the pagination item onClick (function) Callback function to be called when onClick event is fired Applying Pagination component First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, install the bootstrap library using below command, npm install –save bootstrap react-bootstrap Next, open App.css (src/App.css) and remove all the CSS classes. // remove the css Next, create a simple pagination component, SimplePagination (src/Components/SimplePagination.js) as shown below − import React from ”react”; import { Table, Pagination } from ”react-bootstrap”; class SimplePagination extends React.Component { render() { <div>Pagination component</div> } } export default SimplePagination; Next, create a file, users.json under public folder and populate with below user information, [ { “id”:1, “name”:”Fowler”, “age”:18 }, { “id”:2, “name”:”Donnell”, “age”:24 }, { “id”:3, “name”:”Pall”, “age”:26 }, { “id”:4, “name”:”Christos”, “age”:19 }, { “id”:5, “name”:”Dud”, “age”:29 }, { “id”:6, “name”:”Rayner”, “age”:22 }, { “id”:7, “name”:”Somerset”, “age”:31 }, { “id”:8, “name”:”Stavros”, “age”:32 }, { “id”:9, “name”:”Cody”, “age”:19 }, { “id”:10, “name”:”Sharai”, “age”:19 }, { “id”:11, “name”:”Kristo”, “age”:28 }, { “id”:12, “name”:”Harvey”, “age”:27 }, { “id”:13, “name”:”Christen”, “age”:27 }, { “id”:14, “name”:”Hillard”, “age”:19 }, { “id”:15, “name”:”Jaine”, “age”:32 }, { “id”:16, “name”:”Annabel”, “age”:29 }, { “id”:17, “name”:”Hildagarde”, “age”:29 }, { “id”:18, “name”:”Cherlyn”, “age”:18 }, { “id”:19, “name”:”Herold”, “age”:32 }, { “id”:20, “name”:”Gabriella”, “age”:32 }, { “id”:21, “name”:”Jessalyn”, “age”:32 }, { “id”:22, “name”:”Opal”, “age”:31 }, { “id”:23, “name”:”Westbrooke”, “age”:27 }, { “id”:24, “name”:”Morey”, “age”:22 }, { “id”:25, “name”:”Carleton”, “age”:26 }, { “id”:26, “name”:”Cosimo”, “age”:22 }, { “id”:27, “name”:”Petronia”, “age”:23 }, { “id”:28, “name”:”Justino”, “age”:32 }, { “id”:29, “name”:”Verla”, “age”:20 }, { “id”:30, “name”:”Lanita”, “age”:18 }, { “id”:31, “name”:”Karlik”, “age”:23 }, { “id”:32, “name”:”Emmett”, “age”:22 }, { “id”:33, “name”:”Abran”, “age”:26 }, { “id”:34, “name”:”Holly”, “age”:23 }, { “id”:35, “name”:”Beverie”, “age”:23 }, { “id”:36, “name”:”Ingelbert”, “age”:27 }, { “id”:37, “name”:”Kailey”, “age”:30 }, { “id”:38, “name”:”Ralina”, “age”:26 }, { “id”:39, “name”:”Stella”, “age”:29 }, { “id”:40, “name”:”Ronnica”, “age”:20 }, { “id”:41, “name”:”Brucie”, “age”:20 }, { “id”:42, “name”:”Ryan”, “age”:22 }, { “id”:43, “name”:”Fredek”, “age”:20 }, { “id”:44, “name”:”Corliss”, “age”:28 }, { “id”:45, “name”:”Kary”, “age”:32 }, { “id”:46, “name”:”Kaylee”, “age”:21 }, { “id”:47, “name”:”Haskell”, “age”:25 }, { “id”:48, “name”:”Jere”, “age”:29 }, { “id”:49, “name”:”Kathryne”, “age”:31 }, { “id”:50, “name”:”Linnea”, “age”:21 }, { “id”:51, “name”:”Theresina”, “age”:24 }, { “id”:52, “name”:”Arabela”, “age”:32 }, { “id”:53, “name”:”Howie”, “age”:22 }, { “id”:54, “name”:”Merci”, “age”:21 }, { “id”:55, “name”:”Mitchel”, “age”:30 }, { “id”:56, “name”:”Clari”, “age”:18 }, { “id”:57, “name”:”Laurena”, “age”:19 }, { “id”:58, “name”:”Odessa”, “age”:30 }, { “id”:59, “name”:”Pippy”, “age”:25 }, { “id”:60, “name”:”Wilmar”, “age”:23 }, { “id”:61, “name”:”Cherianne”, “age”:24 }, { “id”:62, “name”:”Huberto”, “age”:25 }, { “id”:63, “name”:”Ariella”, “age”:26 }, { “id”:64, “name”:”Lorant”, “age”:30 }, { “id”:65, “name”:”Francesca”, “age”:25 }, { “id”:66, “name”:”Ingamar”, “age”:28 }, { “id”:67, “name”:”Myrta”, “age”:27 }, { “id”:68, “name”:”Nicolette”, “age”:26 }, { “id”:69, “name”:”Petra”, “age”:22 }, { “id”:70, “name”:”Cyrill”, “age”:27 }, { “id”:71, “name”:”Ad”, “age”:23 }, { “id”:72, “name”:”Denys”, “age”:22 }, { “id”:73, “name”:”Karilynn”, “age”:23 }, { “id”:74, “name”:”Gunner”, “age”:30 }, { “id”:75, “name”:”Falkner”, “age”:20 }, { “id”:76, “name”:”Thurston”, “age”:19 }, { “id”:77, “name”:”Codi”, “age”:30 }, { “id”:78, “name”:”Jacob”, “age”:31 }, { “id”:79, “name”:”Gasparo”, “age”:26 }, { “id”:80, “name”:”Mitzi”, “age”:29 }, { “id”:81, “name”:”Rubetta”, “age”:21 }, { “id”:82, “name”:”Clary”, “age”:20 }, { “id”:83, “name”:”Oliviero”, “age”:24 }, { “id”:84, “name”:”Ranique”, “age”:21 }, { “id”:85, “name”:”Shae”, “age”:24 }, { “id”:86, “name”:”Woodrow”, “age”:20 }, { “id”:87, “name”:”Junia”, “age”:31 }, { “id”:88, “name”:”Athene”, “age”:26 }, { “id”:89, “name”:”Veriee”, “age”:18 }, { “id”:90, “name”:”Rickie”, “age”:30 }, { “id”:91, “name”:”Carly”, “age”:23 }, { “id”:92, “name”:”Vern”, “age”:19 }, { “id”:93, “name”:”Trix”, “age”:26 }, { “id”:94, “name”:”Lenore”, “age”:20 }, { “id”:95, “name”:”Hanna”, “age”:30 }, { “id”:96, “name”:”Dominique”, “age”:21 }, { “id”:97, “name”:”Karlotta”, “age”:22 }, { “id”:98, “name”:”Levey”, “age”:20 }, { “id”:99, “name”:”Dalila”, “age”:18 }, { “id”:100, “name”:”Launce”, “age”:21 } ] Next, add a constructor in the SimplePagination component and set initial state as shown below − constructor(props) { super(props); this.state = { users: [], usersToBeShown: [], currentPage: 1 } }; Next, add componentDidMount lifecycle event and add below code to fetch and process the user information. componentDidMount() { fetch(”users.json”) .then((response) => response.json()) .then((data) => { // console.log(data); this.setState({ users: data, pageSize: 3, usersToBeShown: [], pageArray: [] }); this.calculatePaginationDetails(1) }); } Next, implement the pagination logic in the calculatePaginationDetails method as shown below − calculatePaginationDetails = (page) => { console.log(page) let users = this.state.users; let total = users.length; let pages = Math.floor((users.length / this.state.pageSize) + 1); let firstPage = 1;

ReactJS – Table

ReactJS – Table ”; Previous Next React provides table component through third party UI component library. React community provides a large collection of UI / UX components and it is tough to choose the right library for our requirement. Bootstrap UI library is one of the popular choice for the developer and it is extensively used. React Bootstrap (https://react-bootstrap.github.io/) has ported almost all the bootstrap UI components to the React library and it has best support for Table component as well. Let us learn how to use Table component from react-bootstrap library in this chapter. Table component Table component allows the developer to create simple table with bootstrap UI design in a web application. Table component accepts table tags as shown below − thead tbody tfoot Table component accepts a small set of props to customize the table component and they are follows − bordered (boolean) − Adds border to all sides of the table and cell. borderless (boolean) −Removes border to all sides of the table and cell. hover (boolean) − Enables a hover state for each row in the table (tbody). responsive (boolean | string) − Enables vertical scrolling for small devices. sm | md | lg | xl option enables the responsive for relevant devices. For example, sm will be enabled only when the device resolution is very small. size (string) − Enables compact rendering of the table. Possible options are sm, md, etc., striped (boolean | string) − Enables the zebra stripping to all table rows. columns option adds zebra stripping to columns as well. variant (dark) Enables dark variant when dark value is used. bsPrefix (string) − Prefix used to customize the underlying CSS classes. Applying Table component First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, install the bootstrap and react-bootstrap library using below command, npm install –save bootstrap react-bootstrap Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a simple table component, SimpleTable (src/Components/SimpleTable.js) and render a table as shown below − import { Table } from ”react-bootstrap”; function SimpleTable() { return ( <Table striped bordered hover> <thead> <tr> <th>#</th> <th>Name</th> <th>Age</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John</td> <td>25</td> <td>[email protected]</td> </tr> <tr> <td>1</td> <td>Peter</td> <td>15</td> <td>[email protected]</td> </tr> <tr> <td>1</td> <td>Olivia</td> <td>23</td> <td>[email protected]</td> </tr> </tbody> </Table> ); } export default SimpleTable; Here we have, Used striped props to create zebra tables. Used bordered props to enable border around the table and cells. Used hover props to enable hover state. Next, open App component (src/App.js), import the bootstrap css and update the content with bootstrap button as shown below − import ”./App.css” import “bootstrap/dist/css/bootstrap.min.css”; import SimpleTable from ”./Components/SimpleTable” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleTable /> </div> </div> </div> ); } export default App; Here we have, Imported the bootstrap classes using import statement. Rendered our new SimpleTable component. Included the App.css style. Finally, open the application in the browser and check the final result. Table component will be rendered as shown below − Add dark variant and column strip Let us apply dark variant and column strip option in our table component and see how it updates the table design. First of all, open our carousel application and update the SimpleCarousel component as shown below − import { Table } from ”react-bootstrap”; function SimpleTable() { return ( <Table bordered hover striped=”columns” variant=”dark”> // … Here we have, Used striped props with columns to enable column based zebra stripping as well. Used variant props with dark option to enable dark variant of the table design. Next, open the application in the browser and check the final result. Table component will be rendered with column strip and dark variant as shown below − Summary Bootstrap table component provides all necessary options to design a table in a simple, intuitive and flexible manner. Print Page Previous Next Advertisements ”;

ReactJS – Context

ReactJS – Context ”; Previous Next Context is one of the important concept in React. It provides the ability to pass a information from the parent component to all its children to any nested level without passing the information through props in each level. Context will make the code more readable and simple to understand. Context can be used to store information which does not change or have minimal change. Some of the use cases of context are as follows − Application configuration Current authenticated user information Current user setting Language setting Theme / Design configuration by application / users Let us learn how to create context and its usage in this chapter. How context works? Let us learn the basic concept of context and how it works. Context has four parts, Creating a new context Setting context provider in the root component Setting context consumer in the component where we need the context information Accessing context information and using it in render method Let us create an application to better understand context and its usage. Let us create a global context for maintaining theme information in the application root component and use it in our child component. First of all, create and start an application using below command, create-react-app myapp cd myapp npm start Next, create a component, HelloWorld under components folder (src/components/HelloWorld.js) import React from “react”; import ThemeContext from “../ThemeContext”; class HelloWorld extends React.Component { render() { return <div>Hello World</div> } } export default HelloWorld Next, create with a new context (src/ThemeContext.js) for maintaining theme information. import React from ”react” const ThemeContext = React.createContext({ color: ”black”, backgroundColor: ”white” }) export default ThemeContext Here, A new context is created using React.createContext. Context is modeled as an object having style information. Set initial value for color and background of the text. Next, update the root component, App.js by including HelloWorld component and the theme provider with initial value for the theme context. import ”./App.css”; import HelloWorld from ”./components/HelloWorld”; import ThemeContext from ”./ThemeContext” function App() { return ( <ThemeContext.Provider value={{ color: ”white”, backgroundColor: ”green” }}> <HelloWorld /> </ThemeContext.Provider> ); } export default App; Here, the ThemeContext.Provider is used, which is a non-visual component to set the value of the theme context to be used in all its children component. Next, include a context consumer in HelloWorld component and style the hello world message using theme information in HelloWorld component. import React from “react”; import ThemeContext from “../ThemeContext”; class HelloWorld extends React.Component { render() { return ( <ThemeContext.Consumer> {({color, backgroundColor} ) => (<div style={{ color: color, backgroundColor: backgroundColor }}> Hello World </div>) } </ThemeContext.Consumer> ) } } export default HelloWorld Here, Used ThemeContext.Consumer, which is a non-visual component providing access to the current theme context details Used a function expression to get the current context information inside ThemeContext.Consumer Used object deconstruction syntax to get the theme information and set the value in color and backgroundColor variable. Used the theme information to style the component using style props. Finally, open the browser and check the output of the application Summary Context reduces the complexity of maintaining global data in a react application. It provides a clean concept of provider and consumer and simplifies the implementation of context. Print Page Previous Next Advertisements ”;

ReactJS – props Validation

ReactJS – props Validation ”; Previous Next One of the time consuming process in a program is to find the root cause of a bug. In react, props are used extensively. Props of a component will have different source of origin. Some component will have static props, while some component will have dynamic props coming from immediate parent component. One of the source of bugs is that the value of the props does not match the type of the props designed by the developer. This mismatch create a lot of bugs. React provides a lot of option to fix this and one such feature is PropTypes and its validation. We will learn what is PropTypes and how to use it to create a bug free react application in this chapter. PropTypes React community provides a special package, prop-types to address the properties type mismatch problem. prop-types allows the properties of the component to be specified with type through a custom setting (propTypes) inside the component. For example, properties with number type can specified using PropTypes.number option as shown below. Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number } Once the type of the properties is specified, then the React will throw warning during the development phase of the application. Let us include propTypes in our application and see how it helps to catch properties type mismatch issue. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, install prop-types package using node package manager (npm) as shown below − npm i prop-types –save Next, open App.css (src/App.css) and remove all the CSS classes. Then, create a simple component, Sum (src/Components/Sum.js) as shown below − import React from ”react” import PropTypes from ”prop-types” class Sum extends React.Component { render() { return <p>The sum of {this.props.num1} and {this.props.num2} is {parseInt(this.props.num1) + parseInt(this.props.num2)}</p> } } Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number } export default Sum Here, Purpose of the component is to find sum value of the given props (num1 and num2) and show it in the front end. Set the data type of the num1 and num2 as numbers (PropTypes.number) using propTypes. Next, open App component (src/App.js), import the bootstrap css and render the date picker as shown below − import ”./App.css” import Sum from ”./Components/Sum” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <Sum num1=”10″ num2=”John” /> </div> </div> </div> ); } export default App; Here, we have rendered the Sum component with 10 and John as props Finally, open the application in your favorite browser and open the JavaScript console through developer tools. JavaScript throws the warning that the unexpected type is provided as shown below. propTypes only works during development phase to nullify the performance reduction of the application due to additional checking of the props types. This will not affect the performance of the application in production / live setup. Available validators The prop-types supplies a good collection of ready-made validators. They are as follows − PropTypes.array PropTypes.bigint PropTypes.bool PropTypes.func PropTypes.number PropTypes.object PropTypes.string PropTypes.symbol PropTypes.node – Anything that can be rendered PropTypes.element – React component PropTypes.elementType – Type of React component PropTypes.instanceOf() – instance of the specified class propTypes.oneOf([”Value1”, ”valueN”]) – one of Value and ValueN PropTypes.oneOfType([]) – Example, PropTypes.oneOfType([PropTypes.number, PropTypes.bigint]) PropTypes.arrayOf() – Example, PropTypes.arrayOf(PropTypes.number) PropTypes.objectOf() – Example, PropTypes.objectOf(PropTypes.number) PropTypes.func.isRequired propTypes.element.isRequired PropTypes.any.isRequired Custom validator A custom validator can also be created and used to validate the property”s value. Let us consider that the component have a email property and the value should be a valid email address. Then, a validate function can be written and attached to the email property as shown below − Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number, email: function(myProps, myPropName, myComponentName) { if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(myProps[myPropName])) { return new Error( ”Invalid prop value `” + myProps[myPropName] + ”` supplied to” + ” `” + myComponentName + ”/” + myPropName + ”`. Validation failed.” ); } } } Here, /^[^s@]+@[^s@]+.[^s@]+$/ is a simple regex email pattern. myProps represents all properties. myPropName represent the current property being validated. myComponentName represent the name of the component being validated. Similarly, custom validator can be created and used for array and object properties using below function signature − PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) { … }) Here, propValue represents array / object value. key represents the key of the current item. componentName represents the name of the component. propFullName represents the name of the property being validated. Summary Props types is one of the good tool for the developer to write bug free software. It will definitely help the developer to code faster and safer. Print Page Previous Next Advertisements ”;

ReactJS – Higher Order Components

ReactJS – Higher-Order Components ”; Previous Next Since react components are interconnected by composition (having one component inside another) rather than by inheritance, logic used in a react component will not be shared to an another component directly. React community provides multiple option to share the logic between components and one such option is Higher Order Component. HOC is not react api, per se, but a design pattern with no side effects. Let us learn how to use Higher Order Component in this chapter. How to use Higher Order Component Basically, HOC is a function that takes a react component as input and then create a new react component based on the input component and return the newly created (wrapped) component. For example, HOC function may receive a pure data rendering component as input, then return a new component, which will have data fetching capabilities & data rendering capabilities using input component. Let us see how to use HOC and share logic between two component in the step by step manner. Let us consider the scenario of fetching and rendering the data from an external URL. Create a HOC function with one or more input parameters depending on the functionality. The first parameter to the HOC function should be a react component with secondary logic (For example, data rendering logic). The second parameter to the HOC function should be defined as per our requirement. For our data fetching scenario, the data url is the necessary information for fetching the data. So, we should include it as second parameter of our HOC function. function createHOC(WrappedComponent, url) { // create new component using WrappedComponent } Any number of parameter is fine for HOC function, if it is indeed necessary. Create a new component inside the HOC function supporting primary logic (For example, data fetching logic using second url parameter) in it”s componentDidMount event. function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { componentDidMount() { fetch(url) .then((response) => response.json()) .then((data) => { this.setState({ data: data }); }); } } } Render the input component by passing the data fetched from componentDidMount event. function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { render() { return ( <WrappedComponent data={this.state.data} {…this.props} /> ) } } } Return the newly created component. function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { } return DataFetcher; } Create a new component by combining DataFetcher (createFetchHOC) and Wrapped component. const UserListWithFetch = createFetchHOC( UserList, “users.json” ); Finally, use the new component in any place as you wish <UserListWithFetch /> Applying HOC component Let us create a new application by applying the HOC component. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm start Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a new HOC function as shown below − import React from ”react”; function createFetchHOC(WrappedComponent, url) { class DataFetcher extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidMount() { fetch(url) .then((response) => response.json()) .then((data) => { this.setState({ data: data }); }); } render() { return ( <WrappedComponent data={this.state.data} {…this.props} /> ) } } return DataFetcher; } export default createFetchHOC; Next, create a file, users.json (public/users.json) in the public folder to store user information. We will try to fetch it using FetchRenderProps component and show it in our application. [{“id”:1,”name”:”Fowler”,”age”:18}, {“id”:2,”name”:”Donnell”,”age”:24}, {“id”:3,”name”:”Pall”,”age”:26}] Next, create a file, todo_list.json (public/todo_list.json) in the public folder to store todo list information. We will try to fetch it using FetchRenderProps component and show it in our application. [{“id”:1,”title”:”Learn JavaScript”,”is_done”:true}, {“id”:2,”title”:”Learn React”,”is_done”:true}, {“id”:3,”title”:”Learn Typescript”,”is_done”:false}] Next, Create a new component, UserList (src/Components/UserList.js) to render users as shown below − import React from “react”; class UserList extends React.Component { constructor(props) { super(props); } render() { return ( <> <ul> {this.props.data && this.props.data.length && this.props.data.map((item) => <li key={item.id}>{item.name}</li> )} </ul> </> ) } } export default UserList; Here, we have used the data props to render the user list Next, create a new component, TodoList (src/Components/TodoList.js) to render todos as shown below − import React from “react”; class TodoList extends React.Component { constructor(props) { super(props); this.todos = this.props.data } render() { return ( <> <ul> {this.props.data && this.props.data.length && this.props.data.map( (item) => <li key={item.id}>{item.title} {item.is_done && <strong>Done</strong>}</li> )} </ul> </> ) } } export default TodoList; Here, we have used the data props to render the todo list. Next, create a new component, SimpleHOC to render both user list and todo list through single HOC component. import React from “react”; import UserList from “./UserList”; import TodoList from “./TodoList”; import createFetchHOC from “./createFetchHOC”; const UserListWithFetch = createFetchHOC( UserList, “users.json” ); const TodoListWithFetch = createFetchHOC( TodoList, “todo_list.json” ); class SimpleHOC extends React.Component { constructor(props) { super(props); } render() { return ( <> <UserListWithFetch /> <TodoListWithFetch /> </> ) } } export default SimpleHOC; Here we have, Created UserListWithFetch component by combining TodoList and DataFetcher component. Created TodoListWithFetch component by combining Users and DataFetcher component. Next, open App.js and update it with SimpleHOC component. import ”./App.css” import React from ”react”; import SimpleHOC from ”./Components/SimpleHOC” function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleHOC /> </div> </div> </div> ); } export default App; Finally, open the application in the browser and check the final result. The application will render as shown below − Summary Higher Order Component is an efficient method to share logic between components. It is extensively used in many third party component with good success

ReactJS – Creating Components using Properties

ReactJS – Create a Component Using Properties ”; Previous Next As we have already learned in this tutorial before, React is a very flexible library with bendable rules, sometimes, but it strictly follows on one rule: if a component is defined as a function or class, it must act like a pure function with respect to their properties. A pure function in React is defined as a function whose input must not be changed so it does not alter its result. In short, the Props passed to a component are Read-Only. But as the application UIs are dynamic and change their inputs over time, we use “state” concept to handle it. The concept of state allows React components to change their result as a response to changing user actions, network responses, etc. without violating this rule. How to create a component using properties? In this chapter, let us see the steps to create a component using properties − We will first modify our ExpenseEntryItem component and try to use properties. Step 1 − Open our expense-manager application in your favorite editor. Open ExpenseEntryItem file in the src/components folder. Step 2 − Introduce construction function with argument props. constructor(props) { super(props); } Next, change the render method and populate the value from props. render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend date:</b> <em>{this.props.spenddate.tostring()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } Here, name represents the item”s name of type String amount represents the item”s amount of type number spendDate represents the item”s Spend Date of type date category represents the item”s category of type String Now, we have successfully updated the component using properties. import React from ”react” import ”./ExpenseEntryItem.css”; import styles from ”./ExpenseEntryItem.module.css” class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } } export default ExpenseEntryItem; index.js Now, we can use the component by passing all the properties through attributes in the index.js. import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItem from ”./components/ExpenseEntryItem” const name = “Grape Juice” const amount = 30.00 const spendDate = new Date(“2020-10-10”) const category = “Food” ReactDOM.render( <React.StrictMode> <ExpenseEntryItem name={name} amount={amount} spendDate={spendDate} category={category} /> </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. The complete code to do it using CDN in a webpage is as follows − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>React based 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”> class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } } const name = “Grape Juice” const amount = 30.00 const spendDate = new Date(“2020-10-10”) const category = “Food” ReactDOM.render( <ExpenseEntryItem name={name} amount={amount} spendDate={spendDate} category={category} />, document.getElementById(”react-app”) ); </script> </body> </html> Objects as properties Let us learn how to use JavaScript object as attributes in this chapter. Step 1 − Open our expense-manager application in your favorite editor. Open ExpenseEntryItem.js file. Step 2 − Next, change the render() method and access the input object item through this.props.item property. render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em>{this.props.item.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.item.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.item.category}</em></div> </div> ); } Open index.js and represent the expense entry item in JavaScript object. const item = { id: 1, name : “Grape Juice”, amount : 30.5, spendDate: new Date(“2020-10-10”), category: “Food” } Pass the object to the component using curly brace ({}) syntax in the component attributes. <ExpenseEntryItem item={item} /> index.js The complete code of index.js is as follows − import React from ”react”; import ReactDOM from ”react-dom”; import ExpenseEntryItem from ”./components/ExpenseEntryItem” const item = { id: 1, name : “Grape Juice”, amount : 30.5, spendDate: new Date(“2020-10-10”), category: “Food” } ReactDOM.render( <React.StrictMode> <ExpenseEntryItem item={item} /> </React.StrictMode>, document.getElementById(”root”) ); Serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. The complete code to do it using CDN in a webpage is as follows − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <title>React based 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”> class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em>{this.props.item.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.item.spendDate.toString()}</em> </div> <div><b>Category:</b> <em>{this.props.item.category}</em> </div> </div> ); } } const item = { id: 1, name : “Grape Juice”, amount : 30.5, spendDate: new Date(“2020-10-10”), category: “Food” } ReactDOM.render( <ExpenseEntryItem item={item} />, document.getElementById(”react-app”) ); </script> </body> </html> Print Page Previous Next Advertisements ”;