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
Category: reactjs
ReactJS – Introduction to Hooks ”; Previous Next Until React 16.8, function components are simply stateless component. To add state to a component, we need to convert the function component into class based component. Also, function component does not have option to manipulate lifecycle events of a component. To enable state and lifecycle events in the function component, React introduced a new concept called Hooks. Hooks are plain JavaScript functions having access to state and lifecycle events of the component in which it is used / applied. In general, hooks starts with use keyword. React comes with a few built-in hooks and allows the creation of custom hooks as well. Built-in hooks Let us know the list of hooks available in React and its basic usage. useState − Used to manipulate state of the component. useReducer − Advanced version of useState hooks with reducer concept. useEffect − Used to hook into lifecycle of the component. useLayoutEffect − Similar to useEffect, but gets triggered synchronously after all DOM mutation or just before the DOM is going to painted on the screen. useContext − Provides access to the context provider inside a component. useMemo − Used to return a memoized version of a variable / function, which only changes based on supplied predefined set of dependencies. This will reduce the number of recomputation of expensive calculation and improves the performance of the application. useCallback − returns a memoized version of a callback function, which only changes based on supplied predefined set of dependencies. useRef − Provides access to a raw DOM node based on React ref object. useImperativeHandle − Used to expose ref based value in the child component to parent component. useDeferredValue − Used to defer a value similar to debouncing or throttling to defer updates. useDebug − Used to display label for custom hooks in React DevTools. useTransition − Used to identify the pending state of the transition. useId − Used to create unique ID for an element in the application. Applying hooks Let us learn how to use a hook in a function component by creating an application. Create a React application using create-react-app and start the application using below command create-react-app myapp cd myapp npm start Next, let us create a new Function component HelloWorld (src/components/HelloWorld.js), which render an input element and renders a greeting message based on the data entered into the input element by the user. import { useState } from ”react”; export default function HelloWorld() { const [name, setName] = useState(“World”) return ( <div style={{ textAlign: “center”, padding: “5px” }}> <input id=”name” name=”name” value={name} onChange={(e) => setName(e.target.value)} /> <div>Hello {name}</div> </div> ) } Here, useState is a hook, which receives an initial value and returns a state and a function to update the state. it receives World as initial value and returns an array with two items, a) initial value of the state (name) and b) a function to update state (setName). The syntax used is array destruction syntax to get and set the array values into name and setName variables. input is a react input element with an onChange event attached to it. onchange event get the user”s updated values through event.target.value and set it into the current state using setName function. Whenever user updates the input, onchange event fires and update the state, which inturn fires the render function of the component. Next, let us apply our component in our application (App.js) as shown below − import ”./App.css”; import HelloWorld from ”./components/HelloWorld”; function App() { return ( <HelloWorld /> ); } export default App; Finally, open the browser and check the results by changing the input value. The message gets updated whenever the input changes as shown below − Advantages of Hooks Function component have many advantages over class based component when used along with Hooks. They are as follows − Hooks are easy to understand and quick to start coding. The complexity of the application can be kept minimum in a large application. In class based component, the complexity (state management and handling lifecycle events) grows as the project grows. this in class (component) is hard to understand for a beginner in JavaScript programming. Since Function component and hooks don”t depends on this, developers can quickly start coding in React without steep learning curve. Stateful logic can be reused easily between components. Function component can be used along with class based component, which makes it easily adoptable in the existing project of any size. Function component can be written is few lines of code compared to class based components. Disadvantages of Hooks Hooks are alternative methodology to create components and it has its own disadvantages as well. They are as follows − Hooks should be called only at top level and should be avoided inside a condition, loop or nested function. Hooks are specialized features that they may not be best fit for certain situation and we may have to restore to class based component. React handles the internals of hooks without exposing the core for optimization, which makes it less flexible and not suitable for certain scenarios. Summary Hooks are relatively new way of creating components. Large collection of project are still using class based component. Converting the component in those projects from class based to function based is not practically possible and we have to live with it. Instead, we can convert the application in the phased manner. Print Page Previous Next Advertisements ”;
ReactJS – Use Component ”; Previous Next A React component represents a small chunk of user interface in a webpage. The primary job of a React component is to render its user interface and update it whenever its internal state is changed. In addition to rendering the UI, it manages the events belongs to its user interface. To summarize, React component provides below functionalities. Using Components in ReactJS In this chapter, let us use newly created components and enhance our ExpenseEntryItem component. Step 1 − Open our expense-manager application in your favorite editor and open the ExpenseEntryItem.js file. Then, import FormattedMoney and FormattedDate using the following statements. import FormattedMoney from ”./FormattedMoney” import FormattedDate from ”./FormattedDate” Step 2 − Next, update the render method by including FormattedMoney and FormattedDater component. render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em> <FormattedMoney value={this.props.item.amount} /> </em> </div> <div><b>Spend Date:</b> <em> <FormattedDate value={this.props.item.spendDate} /> </em> </div> <div><b>Category:</b> <em>{this.props.item.category}</em></div> </div> ); } Here, we have passed the amount and spendDate through value attribute of the components. The final updated source code of the ExprenseEntryItem component is given below − import React from ”react” import FormattedMoney from ”./FormattedMoney” import FormattedDate from ”./FormattedDate” class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em> <FormattedMoney value={this.props.item.amount} /> </em> </div> <div><b>Spend Date:</b> <em> <FormattedDate value={this.props.item.spendDate} /> </em> </div> <div><b>Category:</b> <em>{this.props.item.category}</em></div> </div> ); } } export default ExpenseEntryItem; index.js Open index.js and call the ExpenseEntryItem component by passing the item object. const item = { id: 1, name : “Grape Juice”, amount : 30.5, spendDate: new Date(“2020-10-10”), category: “Food” } ReactDOM.render( <React.StrictMode> <ExpenseEntryItem item={item} /> </React.StrictMode>, document.getElementById(”root”) ); Next, serve the application using npm command. npm start Open the browser and enter http://localhost:3000 in the address bar and press enter. Print Page Previous Next Advertisements ”;
ReactJS – Code Splitting
ReactJS – Code-Splitting ”; Previous Next Bundling is one of the important stage in a front end application. It bundles all the front end code along with dependency into one large bundle (bundle.js). The final bundle is size optimized by the bundler. Some of the popular bundler are webpack, parcel and rollup. The final bundle will be fine in most cases. If the final bundled code is big, then the bundler can be instructed to bundle the code into multiple item instead of single, big chunk. Let us learn how to hint the bundler to split the code and bundle it separately. Dynamic import Dynamic import instruct the bundler to split the code. Dynamic import is basically fetching the required module based on the necessity. The code to do normal is as shown below − import { round } from ”./math”; console.log(round(67.78)); The same code can be imported dynamically as shown below − import(“./math”).then(math => { console.log(math.round(67.78); }); React Lazy component React provides a function, React.lazy to dynamically import a component. Normally, as we know, a react component will be imported as shown below − import MyComponent from ”./MyComponent”; To import the above component dynamically using React.lazy() function is as shown below − const MyComponent = React.lazy(() => import(”./MyComponent”)); The imported component should be wrapped into a Suspense component to use it in the application. import React, { Suspense } from ”react”; const MyComponent = React.lazy(() => import(”./MyComponent”)); function App() { return ( <div> <Suspense fallback={<div>Loading…</div>}> <MyComponent /> </Suspense> </div> ); } Suspense component is used to load a temporary UI during the loading of the original component. Suspense component includes a fallback props to specify the fallback UI. The fallback UI can be any React element. Sometimes, the dynamic component may fail to load due to network issue or code error. We can use error boundary to handle those situation as shown below − import React, { Suspense } from ”react”; import MyErrorBoundary from ”./MyErrorBoundary”; const MyComponent = React.lazy(() => import(”./MyComponent”)); const AnotherComponent = () => ( <div> <MyErrorBoundary> <Suspense fallback={<div>Loading…</div>}> <section> <MyComponent /> </section> </Suspense> </MyErrorBoundary> </div> ); Here, MyErrorBoundary is wrapped around the Suspense component. If there is any error in loading MyComponent, then MyErrorBoundary handles the error and fallback to the generic UI specified in its component. One of best scenario to apply the code splitting is routing. Routing can be used to apply the code splitting as shown below − import React, { Suspense, lazy } from ”react”; import { BrowserRouter, Routes, Route } from ”react-router-dom”; const Home = lazy(() => import(”./routes/Home”)); const About = lazy(() => import(”./routes/About”)); const App = () => ( <BrowserRouter> <Suspense fallback={<div>Loading…</div>}> <Routes> <Route path=”/” element={<Home />} /> <Route path=”/about” element={<About />} /> </Routes> </Suspense> </BrowserRouter> ); Here, All routes (component) are loaded using React.lazy() feature Since all routes (Home and About ) are loaded through dynamic import, each route will load only the necessary component instead of all components during its initialization. React.lazy() supports only default exports. In React, we can export a component by specifying a dynamic name instead of default keyword as shown below − export const MyComponent = /* … */; To make it usable in React.lazy(), we can reexport the component using default keyword as shown below − export { MyLazyComponent as default } from “./MyComponent.js”; Then, we can import it as usual, import React, { lazy } from ”react”; const MyComponent = lazy(() => import(“./MyComponent.js”)); Applying lazy loading Let us create a new react application to learn how to apply code splitting in this section. First of all, create a new react application and start it using below command. create-react-app myapp cd myapp npm Next, open App.css (src/App.css) and remove all CSS classes. // remove all css classes Next, create a simple hello component, Hello (src/Components/Hello.js) and render a simple message as shown below − import React from “react”; class Hello extends React.Component { constructor(props) { super(props) } render() { return ( <div>Hello, {this.props.name}</div> ); } } export default Hello; Here, we have used the name props to render the hello message with the given name. Next, create a simple component, SimpleErrorBoundary (src/Components/SimpleErrorBoundary.js) and render either fallback UI during error or children components as shown below − import React from “react”; class SimpleErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log(error); console.log(errorInfo); } render() { if (this.state.hasError) { return <h1>Please contact the administrator.</h1>; } return this.props.children; } } export default SimpleErrorBoundary; Here, hasError is a state variable initialized with false value. getDerivedStateFromError updates the error state when there is an error. componentDidCatch logs the error into the console. render will render either error UI or children based on the error in the application. Next, open App component (src/App.js), and load the hello component through React.lazy() as shown below − import ”./App.css” import React, { Suspense, lazy } from ”react”; import SimpleErrorBoundary from ”./Components/SimpleErrorBoundary”; const Hello = lazy(() => import(”./Components/Hello”)); function App() { return ( <div className=”container”> <div style={{ padding: “10px” }}> <div> <SimpleErrorBoundary> <Suspense fallback=”<div>loading…</div>”> <Hello name=”Peter” /> </Suspense> </SimpleErrorBoundary> </div> </div> </div> ); } export default App; Here we have, Imported lazy and Suspense component from the react package. Used Hello component by wrapping it with Suspense and SimpleErrorBoundary component. Finally, open the application in the browser and check the final result. The lazy load does not have have any visible changes in the front end. It will render the
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
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 – State Management
ReactJS – State Management ”; Previous Next State management is one of the important and unavoidable features of any dynamic application. React provides a simple and flexible API to support state management in a React component. Let us understand how to maintain state in React application in this chapter. What is state? State represents the value of a dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. The internal data represents the state of a React component and can be accessed using this.state member variable of the component. Whenever the state of the component is changed, the component will re-render itself by calling the render() method along with the new state. A simple example to better understand the state management is to analyse a real-time clock component. The clock component primary job is to show the date and time of a location at the given instance. As the current time will change every second, the clock component should maintain the current date and time in it”s state. As the state of the clock component changes every second, the clock”s render() method will be called every second and the render() method show the current time using it”s current state. The simple representation of the state is as follows − { date: ”2020-10-10 10:10:10” } Let us create a new Clock component in the Stateless Component chapter. Defining a State State in React can be used with functional and class components. To work with state in a component, there must exist a starting point, i.e. initial state. This initial state of a component must be defined in the constructor of the component”s class. Following is the syntax to define a state of any Class − state = {attribute: “value”}; Let us look at a sample code for a class component with an initial state − Class SampleClass extends React.Component { constructor(props) { super(props); this.state = { name : “John Doe” }; } } Creating a state Object React components have a built-in state object. The state object is used to store all the property values that belong to the component in which this state is defined. When the state object changes, the component re-renders. Let us look at a sample code to demonstrate how to create a state object in React. Class BookClass extends React.Component { constructor(props) { super(props); this.state = { name : “John Doe” }; } render() { return ( <div> <h1>Name of the Author</h1> </div> ); } } To understand state management better, check the following chapters. State management API State management using React Hooks Component Life cycle Component life cycle using React Hooks Layout in component Pagination Material UI Print Page Previous Next Advertisements ”;
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 ”;