Author: saqibkhan

  •  Performance Enhancement

    ReactJS improves performance due to virtual DOM. The DOM is a cross-platform and programming API which deals with HTML, XML or XHTML. Most of the developers faced the problem when the DOM was updated, which slowed down the performance of the application. ReactJS solved this problem by introducing virtual DOM. The React Virtual DOM exists entirely in memory and is a representation of the web browser’s DOM. Due to this, when we write a React component, we did not write directly to the DOM. Instead, we are writing virtual components that react will turn into the DOM, leading to smoother and faster performance.

  • Reusable Components

    A ReactJS web application is made up of multiple components, and each component has its own logic and controls. These components are responsible for outputting a small, reusable piece of HTML code which can be reused wherever you need them. The reusable code helps to make your apps easier to develop and maintain. These Components can be nested with other components to allow complex applications to be built of simple building blocks. ReactJS uses virtual DOM based mechanism to fill data in HTML DOM. The virtual DOM works fast as it only changes individual DOM elements instead of reloading complete DOM every time.

  • Creating Dynamic Web Applications Becomes Easier

    To create a dynamic web application specifically with HTML strings was tricky because it requires a complex coding, but React JS solved that issue and makes it easier. It provides less coding and gives more functionality. It makes use of the JSX(JavaScript Extension), which is a particular syntax letting HTML quotes and HTML tag syntax to render particular subcomponents. It also supports the building of machine-readable codes.

  • CSS

    CSS in React is used to style the React App or Component. The style attribute is the most used attribute for styling in React applications, which adds dynamically-computed styles at render time. It accepts a JavaScript object in camelCased properties rather than a CSS string. There are many ways available to add styling to your React App or Component with CSS. Here, we are going to discuss mainly four ways to style React Components, which are given below:

    1. Inline Styling
    2. CSS Stylesheet
    3. CSS Module
    4. Styled Components

    1. Inline Styling

    The inline styles are specified with a JavaScript object in camelCase version of the style name. Its value is the style?s value, which we usually take in a string.

    Example

    App.js

    import React from 'react';  
    
    import ReactDOM from 'react-dom';  
    
      
    
    class App extends React.Component {  
    
      render() {  
    
        return (  
    
          <div>  
    
          <h1 style={{color: "Green"}}>Hello JavaTpoint!</h1>  
    
          <p>Here, you can find all CS tutorials.</p>  
    
          </div>  
    
        );  
    
      }  
    
    }  
    
    export default App; 

      Note: You can see in the above example, we have used two curly braces in:
      <h1 style={{color: “Green”}}>Hello JavaTpoint!</h1>.
      It is because, in JSX, JavaScript expressions are written inside curly braces, and JavaScript objects also use curly braces, so the above styling is written inside two sets of curly braces {{}}.

      Output

      React CSS

      camelCase Property Name

      If the properties have two names, like background-color, it must be written in camel case syntax.

      Example

      App.js

      import React from 'react';  
      
      import ReactDOM from 'react-dom';  
      
        
      
      class App extends React.Component {  
      
        render() {  
      
          return (  
      
            <div>  
      
            <h1 style={{color: "Red"}}>Hello JavaTpoint!</h1>  
      
            <p style={{backgroundColor: "lightgreen"}}>Here, you can find all CS tutorials.</p>  
      
            </div>  
      
          );  
      
        }  
      
      }  
      
      export default App;

      Output

      React CSS

      Using JavaScript Object

      The inline styling also allows us to create an object with styling information and refer it in the style attribute.

      Example

      App.js

      import React from 'react';  
      
      import ReactDOM from 'react-dom';  
      
        
      
      class App extends React.Component {  
      
        render() {  
      
          const mystyle = {  
      
            color: "Green",  
      
            backgroundColor: "lightBlue",  
      
            padding: "10px",  
      
            fontFamily: "Arial"  
      
          };  
      
          return (  
      
            <div>  
      
            <h1 style={mystyle}>Hello JavaTpoint</h1>  
      
            <p>Here, you can find all CS tutorials.</p>  
      
            </div>  
      
          );  
      
        }  
      
      }  
      
      export default App;  

        Output

        React CSS

        2. CSS Stylesheet

        You can write styling in a separate file for your React application, and save the file with a .css extension. Now, you can import this file in your application.

        Example

        App.js

        import React from 'react';  
        
        import ReactDOM from 'react-dom';  
        
        import './App.css';  
        
          
        
        class App extends React.Component {  
        
          render() {  
        
            return (  
        
              <div>  
        
              <h1>Hello JavaTpoint</h1>  
        
              <p>Here, you can find all CS tutorials.</p>  
        
              </div>  
        
            );  
        
          }  
        
        }  
        
        export default App;

        App.css

        body {  
        
          background-color: #008080;  
        
          color: yellow;  
        
          padding: 40px;  
        
          font-family: Arial;  
        
          text-align: center;  
        
        }  

          Index.html

          <!DOCTYPE html>  
          
          <html lang="en">  
          
            <head>  
          
              <meta charset="utf-8" />  
          
              <meta name="viewport"  
          
                content="width=device-width, initial-scale=1" />  
          
              <title>React App</title>  
          
            </head>  
          
            <body>  
          
              <div id="app"></div>  
          
            </body>  
          
          </html> 

            Output

            React CSS

            3. CSS Module

            CSS Module is another way of adding styles to your application. It is a CSS file where all class names and animation names are scoped locally by default. It is available only for the component which imports it, means any styling you add can never be applied to other components without your permission, and you never need to worry about name conflicts. You can create CSS Module with the .module.css extension like a myStyles.module.css name.

            Example

            App.js

            import React from 'react';  
            
            import ReactDOM from 'react-dom';  
            
            import styles from './myStyles.module.css';   
            
              
            
            class App extends React.Component {  
            
              render() {  
            
                return (  
            
                  <div>  
            
                  <h1 className={styles.mystyle}>Hello JavaTpoint</h1>  
            
                  <p className={styles.parastyle}>It provides great CS tutorials.</p>  
            
                  </div>  
            
                );  
            
              }  
            
            }  
            
            export default App;  

              myStyles.module.css

              .mystyle {  
              
                background-color: #cdc0b0;  
              
                color: Red;  
              
                padding: 10px;  
              
                font-family: Arial;  
              
                text-align: center;  
              
              }  
              
                
              
              .parastyle{  
              
                color: Green;  
              
                font-family: Arial;  
              
                font-size: 35px;  
              
                text-align: center;  
              
              }  

                Output

                React CSS

                4. Styled Components

                Styled-components is a library for React. It uses enhance CSS for styling React component systems in your application, which is written with a mixture of JavaScript and CSS.

                The styled-components provides:

                • Automatic critical CSS
                • No class name bugs
                • Easier deletion of CSS
                • Simple dynamic styling
                • Painless maintenance

                Installation

                The styled-components library takes a single command to install in your React application. which is:

                $ npm install styled-components --save  

                Example

                Here, we create a variable by selecting a particular HTML element such as <div><Title>, and <paragraph> where we store our style attributes. Now we can use the name of our variable as a wrapper <Div></Div> kind of React component.

                App.js

                import React from 'react';  
                
                import ReactDOM from 'react-dom';  
                
                import styled from 'styled-components';  
                
                  
                
                class App extends React.Component {  
                
                  render() {  
                
                    const Div:any = styled.div`  
                
                            margin: 20px;  
                
                            border: 5px dashed green;  
                
                            &:hover {  
                
                            background-color: ${(props:any) => props.hoverColor};  
                
                            }  
                
                            `;  
                
                    const Title = styled.h1`  
                
                            font-family: Arial;  
                
                            font-size: 35px;  
                
                            text-align: center;  
                
                            color: palevioletred;  
                
                            `;  
                
                    const Paragraph = styled.p`  
                
                            font-size: 25px;  
                
                            text-align: center;  
                
                            background-Color: lightgreen;  
                
                            `;  
                
                    return (  
                
                       <div>            
                
                            <Title>Styled Components Example</Title>  
                
                            <p></p>  
                
                            <Div hoverColor="Orange">  
                
                                 <Paragraph>Hello JavaTpoint!!</Paragraph>  
                
                            </Div>  
                
                        </div>  
                
                    );  
                
                  }  
                
                }  
                
                export default App;  

                  Output

                  Now, execute the App.js file, we will get the output as shown below.

                  React CSS

                  When we move the mouse pointer over the image, its color will be changed, as shown in the below image.

                  React CSS
                1. Router

                  Routing is a process in which a user is directed to different pages based on their action or request. ReactJS Router is mainly used for developing Single Page Web Applications. React Router is used to define multiple routes in the application. When a user types a specific URL into the browser, and if this URL path matches any ‘route’ inside the router file, the user will be redirected to that particular route.

                  React Router is a standard library system built on top of the React and used to create routing in the React application using React Router Package. It provides the synchronous URL on the browser with data that will be displayed on the web page. It maintains the standard structure and behavior of the application and mainly used for developing single page web applications.

                  Need of React Router

                  React Router plays an important role to display multiple views in a single page application. Without React Router, it is not possible to display multiple views in React applications. Most of the social media websites like Facebook, Instagram uses React Router for rendering multiple views.

                  React Router Installation

                  React contains three different packages for routing. These are:

                  1. react-router: It provides the core routing components and functions for the React Router applications.
                  2. react-router-native: It is used for mobile applications.
                  3. react-router-dom: It is used for web applications design.

                  It is not possible to install react-router directly in your application. To use react routing, first, you need to install react-router-dom modules in your application. The below command is used to install react router dom.

                  $ npm install react-router-dom --save   

                  Components in React Router

                  There are two types of router components:

                  • <BrowserRouter>: It is used for handling the dynamic URL.
                  • <HashRouter>: It is used for handling the static request.

                  Example

                  Step-1: In our project, we will create two more components along with App.js, which is already present.

                  About.js

                  import React from 'react'  
                  
                  class About extends React.Component {  
                  
                    render() {  
                  
                      return <h1>About</h1>  
                  
                    }  
                  
                  }  
                  
                  export default About 

                    Contact.js

                    import React from 'react'  
                    
                    class Contact extends React.Component {  
                    
                      render() {  
                    
                        return <h1>Contact</h1>  
                    
                      }  
                    
                    }  
                    
                    export default Contact  

                      App.js

                      import React from 'react'  
                      
                      class App extends React.Component {  
                      
                        render() {  
                      
                          return (  
                      
                            <div>  
                      
                              <h1>Home</h1>  
                      
                            </div>  
                      
                          )  
                      
                        }  
                      
                      }  
                      
                      export default App  

                        Step-2: For Routing, open the index.js file and import all the three component files in it. Here, you need to import line: import { Route, Link, BrowserRouter as Router } from ‘react-router-dom’ which helps us to implement the Routing. Now, our index.js file looks like below.

                        What is Route?

                        It is used to define and render component based on the specified path. It will accept components and render to define what should be rendered.

                        Index.js

                        import React from 'react';  
                        
                        import ReactDOM from 'react-dom';  
                        
                        import { Route, Link, BrowserRouter as Router } from 'react-router-dom'  
                        
                        import './index.css';  
                        
                        import App from './App';  
                        
                        import About from './about'  
                        
                        import Contact from './contact'  
                        
                          
                        
                        const routing = (  
                        
                          <Router>  
                        
                            <div>  
                        
                              <h1>React Router Example</h1>  
                        
                              <Route path="/" component={App} />  
                        
                              <Route path="/about" component={About} />  
                        
                              <Route path="/contact" component={Contact} />  
                        
                            </div>  
                        
                          </Router>  
                        
                        )  
                        
                        ReactDOM.render(routing, document.getElementById('root')); 

                          Step-3: Open command prompt, go to your project location, and then type npm start. You will get the following screen.

                          React Router

                          Now, if you enter manually in the browser: localhost:3000/about, you will see About component is rendered on the screen.

                          React Router

                          Step-4: In the above screen, you can see that Home component is still rendered. It is because the home path is ‘/‘ and about path is ‘/about‘, so you can observe that slash is common in both paths which render both components. To stop this behavior, you need to use the exact prop. It can be seen in the below example.

                          Index.js

                          import React from 'react';  
                          
                          import ReactDOM from 'react-dom';  
                          
                          import { Route, Link, BrowserRouter as Router } from 'react-router-dom'  
                          
                          import './index.css';  
                          
                          import App from './App';  
                          
                          import About from './about'  
                          
                          import Contact from './contact'  
                          
                            
                          
                          const routing = (  
                          
                            <Router>  
                          
                              <div>  
                          
                                <h1>React Router Example</h1>  
                          
                                <Route exact path="/" component={App} />  
                          
                                <Route path="/about" component={About} />  
                          
                                <Route path="/contact" component={Contact} />  
                          
                              </div>  
                          
                            </Router>  
                          
                          )  
                          
                          ReactDOM.render(routing, document.getElementById('root'));  

                            Output

                            React Router

                            Adding Navigation using Link component

                            Sometimes, we want to need multiple links on a single page. When we click on any of that particular Link, it should load that page which is associated with that path without reloading the web page. To do this, we need to import <Link> component in the index.js file.

                            What is < Link> component?

                            This component is used to create links which allow to navigate on different URLs and render its content without reloading the webpage.

                            Example

                            Index.js

                            import React from 'react';  
                            
                            import ReactDOM from 'react-dom';  
                            
                            import { Route, Link, BrowserRouter as Router } from 'react-router-dom'  
                            
                            import './index.css';  
                            
                            import App from './App';  
                            
                            import About from './about'  
                            
                            import Contact from './contact'  
                            
                              
                            
                            const routing = (  
                            
                              <Router>  
                            
                                <div>  
                            
                                  <h1>React Router Example</h1>  
                            
                                  <ul>  
                            
                                    <li>  
                            
                                      <Link to="/">Home</Link>  
                            
                                    </li>  
                            
                                    <li>  
                            
                                      <Link to="/about">About</Link>  
                            
                                    </li>  
                            
                                    <li>  
                            
                                      <Link to="/contact">Contact</Link>  
                            
                                    </li>  
                            
                                  </ul>  
                            
                                  <Route exact path="/" component={App} />  
                            
                                  <Route path="/about" component={About} />  
                            
                                  <Route path="/contact" component={Contact} />  
                            
                                </div>  
                            
                              </Router>  
                            
                            )  
                            
                            ReactDOM.render(routing, document.getElementById('root'));

                            Output

                            React Router

                            After adding Link, you can see that the routes are rendered on the screen. Now, if you click on the About, you will see URL is changing and About component is rendered.

                            React Router

                            Now, we need to add some styles to the Link. So that when we click on any particular link, it can be easily identified which Link is active. To do this react router provides a new trick NavLink instead of Link. Now, in the index.js file, replace Link from Navlink and add properties activeStyle. The activeStyle properties mean when we click on the Link, it should have a specific style so that we can differentiate which one is currently active.

                            import React from 'react';  
                            
                            import ReactDOM from 'react-dom';  
                            
                            import { BrowserRouter as Router, Route, Link, NavLink } from 'react-router-dom'  
                            
                            import './index.css';  
                            
                            import App from './App';  
                            
                            import About from './about'  
                            
                            import Contact from './contact'  
                            
                              
                            
                            const routing = (  
                            
                              <Router>  
                            
                                <div>  
                            
                                  <h1>React Router Example</h1>  
                            
                                  <ul>  
                            
                                    <li>  
                            
                                      <NavLink to="/" exact activeStyle={  
                            
                                         {color:'red'}  
                            
                                      }>Home</NavLink>  
                            
                                    </li>  
                            
                                    <li>  
                            
                                      <NavLink to="/about" exact activeStyle={  
                            
                                         {color:'green'}  
                            
                                      }>About</NavLink>  
                            
                                    </li>  
                            
                                    <li>  
                            
                                      <NavLink to="/contact" exact activeStyle={  
                            
                                         {color:'magenta'}  
                            
                                      }>Contact</NavLink>  
                            
                                    </li>  
                            
                                  </ul>  
                            
                                  <Route exact path="/" component={App} />  
                            
                                  <Route path="/about" component={About} />  
                            
                                  <Route path="/contact" component={Contact} />  
                            
                                </div>  
                            
                              </Router>  
                            
                            )  
                            
                            ReactDOM.render(routing, document.getElementById('root')); 

                              Output

                              When we execute the above program, we will get the following screen in which we can see that Home link is of color Red and is the only currently active link.

                              React Router

                              Now, when we click on About link, its color shown green that is the currently active link.

                              React Router

                              <Link> vs <NavLink>

                              The Link component allows navigating the different routes on the websites, whereas NavLink component is used to add styles to the active routes.

                              React Router Switch

                              The <Switch> component is used to render components only when the path will be matched. Otherwise, it returns to the not found component.

                              To understand this, first, we need to create a notfound component.

                              notfound.js

                              import React from 'react'  
                              
                              const Notfound = () => <h1>Not found</h1>  
                              
                              export default Notfound  

                                Now, importcomponent in the index.js file. It can be seen in the below code.

                                Index.js

                                import React from 'react';  
                                
                                import ReactDOM from 'react-dom';  
                                
                                import { BrowserRouter as Router, Route, Link, NavLink, Switch } from 'react-router-dom'  
                                
                                import './index.css';  
                                
                                import App from './App';  
                                
                                import About from './about'  
                                
                                import Contact from './contact'  
                                
                                import Notfound from './notfound'  
                                
                                  
                                
                                const routing = (  
                                
                                  <Router>  
                                
                                    <div>  
                                
                                      <h1>React Router Example</h1>  
                                
                                      <ul>  
                                
                                        <li>  
                                
                                          <NavLink to="/" exact activeStyle={  
                                
                                             {color:'red'}  
                                
                                          }>Home</NavLink>  
                                
                                        </li>  
                                
                                        <li>  
                                
                                          <NavLink to="/about" exact activeStyle={  
                                
                                             {color:'green'}  
                                
                                          }>About</NavLink>  
                                
                                        </li>  
                                
                                        <li>  
                                
                                          <NavLink to="/contact" exact activeStyle={  
                                
                                             {color:'magenta'}  
                                
                                          }>Contact</NavLink>  
                                
                                        </li>  
                                
                                      </ul>  
                                
                                      <Switch>  
                                
                                         <Route exact path="/" component={App} />  
                                
                                         <Route path="/about" component={About} />  
                                
                                         <Route path="/contact" component={Contact} />  
                                
                                         <Route component={Notfound} />  
                                
                                      </Switch>  
                                
                                    </div>  
                                
                                  </Router>  
                                
                                )  
                                
                                ReactDOM.render(routing, document.getElementById('root')); 

                                  Output

                                  If we manually enter the wrong path, it will give the not found error.

                                  React Router

                                  React Router <Redirect>

                                  A <Redirect> component is used to redirect to another route in our application to maintain the old URLs. It can be placed anywhere in the route hierarchy.

                                  Nested Routing in React

                                  Nested routing allows you to render sub-routes in your application. It can be understood in the below example.

                                  Example

                                  index.js

                                  import React from 'react';  
                                  
                                  import ReactDOM from 'react-dom';  
                                  
                                  import { BrowserRouter as Router, Route, Link, NavLink, Switch } from 'react-router-dom'  
                                  
                                  import './index.css';  
                                  
                                  import App from './App';  
                                  
                                  import About from './about'  
                                  
                                  import Contact from './contact'  
                                  
                                  import Notfound from './notfound'  
                                  
                                    
                                  
                                  const routing = (  
                                  
                                    <Router>  
                                  
                                      <div>  
                                  
                                        <h1>React Router Example</h1>  
                                  
                                        <ul>  
                                  
                                          <li>  
                                  
                                            <NavLink to="/" exact activeStyle={  
                                  
                                               {color:'red'}  
                                  
                                            }>Home</NavLink>  
                                  
                                          </li>  
                                  
                                          <li>  
                                  
                                            <NavLink to="/about" exact activeStyle={  
                                  
                                               {color:'green'}  
                                  
                                            }>About</NavLink>  
                                  
                                          </li>  
                                  
                                          <li>  
                                  
                                            <NavLink to="/contact" exact activeStyle={  
                                  
                                               {color:'magenta'}  
                                  
                                            }>Contact</NavLink>  
                                  
                                          </li>  
                                  
                                        </ul>  
                                  
                                        <Switch>  
                                  
                                           <Route exact path="/" component={App} />  
                                  
                                           <Route path="/about" component={About} />  
                                  
                                           <Route path="/contact" component={Contact} />  
                                  
                                           <Route component={Notfound} />  
                                  
                                        </Switch>  
                                  
                                      </div>  
                                  
                                    </Router>  
                                  
                                  )  
                                  
                                  ReactDOM.render(routing, document.getElementById('root'));  

                                    In the contact.js file, we need to import the React Router component to implement the subroutes.

                                    contact.js

                                    import React from 'react'  
                                    
                                    import { Route, Link } from 'react-router-dom'  
                                    
                                      
                                    
                                    const Contacts = ({ match }) => <p>{match.params.id}</p>  
                                    
                                      
                                    
                                    class Contact extends React.Component {  
                                    
                                      render() {  
                                    
                                        const { url } = this.props.match  
                                    
                                        return (  
                                    
                                          <div>  
                                    
                                            <h1>Welcome to Contact Page</h1>  
                                    
                                            <strong>Select contact Id</strong>  
                                    
                                            <ul>  
                                    
                                              <li>  
                                    
                                                <Link to="/contact/1">Contacts 1 </Link>  
                                    
                                              </li>  
                                    
                                              <li>  
                                    
                                                <Link to="/contact/2">Contacts 2 </Link>  
                                    
                                              </li>  
                                    
                                              <li>  
                                    
                                                <Link to="/contact/3">Contacts 3 </Link>  
                                    
                                              </li>  
                                    
                                              <li>  
                                    
                                                <Link to="/contact/4">Contacts 4 </Link>  
                                    
                                              </li>  
                                    
                                            </ul>  
                                    
                                            <Route path="/contact/:id" component={Contacts} />  
                                    
                                          </div>  
                                    
                                        )  
                                    
                                      }  
                                    
                                    }  
                                    
                                    export default Contact  

                                      Output

                                      When we execute the above program, we will get the following output.

                                      React Router

                                      After clicking the Contact link, we will get the contact list. Now, selecting any contact, we will get the corresponding output. It can be shown in the below example.

                                      React Router

                                      Benefits Of React Router

                                      The benefits of React Router is given below:

                                      • In this, it is not necessary to set the browser history manually.
                                      • Link uses to navigate the internal links in the application. It is similar to the anchor tag.
                                      • It uses Switch feature for rendering.
                                      • The Router needs only a Single Child element.
                                      • In this, every component is specified in.
                                    1. Easy to Learn and USe

                                      ReactJS is much easier to learn and use. It comes with a good supply of documentation, tutorials, and training resources. Any developer who comes from a JavaScript background can easily understand and start creating web apps using React in a few days. It is the V(view part) in the MVC (Model-View-Controller) model, and referred to as ?one of the JavaScript frameworks.? It is not fully featured but has the advantage of open-source JavaScript User Interface(UI) library, which helps to execute the task in a better manner.

                                    2. Fragments

                                      In React, whenever you want to render something on the screen, you need to use a render method inside the component. This render method can return single elements or multiple elements. The render method will only render a single root node inside it at a time. However, if you want to return multiple elements, the render method will require a ‘div‘ tag and put the entire content or elements inside it. This extra node to the DOM sometimes results in the wrong formatting of your HTML output and also not loved by the many developers.

                                      Example

                                      // Rendering with div tag  
                                      
                                      class App extends React.Component {   
                                      
                                           render() {    
                                      
                                            return (   
                                      
                                               //Extraneous div element   
                                      
                                               <div>  
                                      
                                                 <h2> Hello World! </h2>   
                                      
                                                 <p> Welcome to the JavaTpoint. </p>   
                                      
                                               </div>   
                                      
                                            );   
                                      
                                           }   
                                      
                                      } 

                                        To solve this problem, React introduced Fragments from the 16.2 and above version. Fragments allow you to group a list of children without adding extra nodes to the DOM.

                                        Syntax

                                        <React.Fragment>  
                                        
                                              <h2> child1 </h2>   
                                        
                                            <p> child2 </p>   
                                        
                                              .. ..... .... ...  
                                        
                                        </React.Fragment> 

                                          Example

                                          // Rendering with fragments tag  
                                          
                                          class App extends React.Component {   
                                          
                                              render() {   
                                          
                                               return (   
                                          
                                                 <React.Fragment>  
                                          
                                                      <h2> Hello World! </h2>   
                                          
                                                  <p> Welcome to the JavaTpoint. </p>   
                                          
                                                   </React.Fragment>  
                                          
                                               );   
                                          
                                              }   
                                          
                                          }  

                                            Why we use Fragments?

                                            The main reason to use Fragments tag is:

                                            1. It makes the execution of code faster as compared to the div tag.
                                            2. It takes less memory.

                                            Fragments Short Syntax

                                            There is also another shorthand exists for declaring fragments for the above method. It looks like empty tag in which we can use of ‘<>’ and ” instead of the ‘React.Fragment‘.

                                            Example

                                            //Rendering with short syntax   
                                            
                                            class Columns extends React.Component {   
                                            
                                              render() {   
                                            
                                                return (   
                                            
                                                  <>    
                                            
                                                    <h2> Hello World! </h2>   
                                            
                                                    <p> Welcome to the JavaTpoint </p>   
                                            
                                                  </>   
                                            
                                                );   
                                            
                                              }   
                                            
                                            }   

                                              Keyed Fragments

                                              The shorthand syntax does not accept key attributes. You need a key for mapping a collection to an array of fragments such as to create a description list. If you need to provide keys, you have to declare the fragments with the explicit <React.Fragment> syntax.

                                              Note: Key is the only attributes that can be passed with the Fragments.

                                              Example

                                              Function  = (props) {  
                                              
                                                return (  
                                              
                                                  <Fragment>  
                                              
                                                    {props.items.data.map(item => (  
                                              
                                                      // Without the 'key', React will give a key warning  
                                              
                                                      <React.Fragment key={item.id}>  
                                              
                                                        <h2>{item.name}</h2>  
                                              
                                                        <p>{item.url}</p>  
                                              
                                                        <p>{item.description}</p>  
                                              
                                                      </React.Fragment>  
                                              
                                                    ))}  
                                              
                                                  </Fragment>  
                                              
                                                )  
                                              
                                              }
                                            1. Refs

                                              Refs is the shorthand used for references in React. It is similar to keys in React. It is an attribute which makes it possible to store a reference to particular DOM nodes or React elements. It provides a way to access React DOM nodes or React elements and how to interact with it. It is used when we want to change the value of a child component, without making the use of props.

                                              When to Use Refs

                                              Refs can be used in the following cases:

                                              • When we need DOM measurements such as managing focus, text selection, or media playback.
                                              • It is used in triggering imperative animations.
                                              • When integrating with third-party DOM libraries.
                                              • It can also use as in callbacks.

                                              When to not use Refs

                                              • Its use should be avoided for anything that can be done declaratively. For example, instead of using open() and close() methods on a Dialog component, you need to pass an isOpen prop to it.
                                              • You should have to avoid overuse of the Refs.

                                              How to create Refs

                                              In React, Refs can be created by using React.createRef(). It can be assigned to React elements via the ref attribute. It is commonly assigned to an instance property when a component is created, and then can be referenced throughout the component.

                                              class MyComponent extends React.Component {  
                                              
                                                constructor(props) {  
                                              
                                                  super(props);  
                                              
                                                  this.callRef = React.createRef();  
                                              
                                                }  
                                              
                                                render() {  
                                              
                                                  return <div ref={this.callRef} />;  
                                              
                                                }  
                                              
                                              }  

                                                How to access Refs

                                                In React, when a ref is passed to an element inside render method, a reference to the node can be accessed via the current attribute of the ref.

                                                const node = this.callRef.current;  

                                                Refs current Properties

                                                The ref value differs depending on the type of the node:

                                                • When the ref attribute is used in HTML element, the ref created with React.createRef() receives the underlying DOM element as its current property.
                                                • If the ref attribute is used on a custom class component, then ref object receives the mounted instance of the component as its current property.
                                                • The ref attribute cannot be used on function components because they don’t have instances.

                                                Add Ref to DOM elements

                                                In the below example, we are adding a ref to store the reference to a DOM node or element.

                                                import React, { Component } from 'react';  
                                                
                                                import { render } from 'react-dom';  
                                                
                                                   
                                                
                                                class App extends React.Component {  
                                                
                                                  constructor(props) {  
                                                
                                                    super(props);  
                                                
                                                    this.callRef = React.createRef();  
                                                
                                                    this.addingRefInput = this.addingRefInput.bind(this);  
                                                
                                                  }  
                                                
                                                   
                                                
                                                  addingRefInput() {  
                                                
                                                    this.callRef.current.focus();  
                                                
                                                  }  
                                                
                                                   
                                                
                                                  render() {  
                                                
                                                    return (  
                                                
                                                      <div>  
                                                
                                                        <h2>Adding Ref to DOM element</h2>  
                                                
                                                        <input  
                                                
                                                          type="text"  
                                                
                                                          ref={this.callRef} />  
                                                
                                                        <input  
                                                
                                                          type="button"  
                                                
                                                          value="Add text input"  
                                                
                                                          onClick={this.addingRefInput}  
                                                
                                                        />  
                                                
                                                      </div>  
                                                
                                                    );  
                                                
                                                  }  
                                                
                                                }  
                                                
                                                export default App;  

                                                  Output

                                                  React Refs

                                                  Add Ref to Class components

                                                  In the below example, we are adding a ref to store the reference to a class component.

                                                  Example

                                                  import React, { Component } from 'react';  
                                                  
                                                  import { render } from 'react-dom';  
                                                  
                                                     
                                                  
                                                  function CustomInput(props) {  
                                                  
                                                    let callRefInput = React.createRef();  
                                                  
                                                     
                                                  
                                                    function handleClick() {  
                                                  
                                                      callRefInput.current.focus();  
                                                  
                                                    }  
                                                  
                                                     
                                                  
                                                    return (  
                                                  
                                                      <div>  
                                                  
                                                        <h2>Adding Ref to Class Component</h2>  
                                                  
                                                        <input  
                                                  
                                                          type="text"  
                                                  
                                                          ref={callRefInput} />  
                                                  
                                                        <input  
                                                  
                                                          type="button"  
                                                  
                                                          value="Focus input"  
                                                  
                                                          onClick={handleClick}  
                                                  
                                                        />  
                                                  
                                                      </div>  
                                                  
                                                    );  
                                                  
                                                  }  
                                                  
                                                  class App extends React.Component {  
                                                  
                                                    constructor(props) {  
                                                  
                                                      super(props);  
                                                  
                                                      this.callRefInput = React.createRef();  
                                                  
                                                    }  
                                                  
                                                     
                                                  
                                                    focusRefInput() {  
                                                  
                                                      this.callRefInput.current.focus();  
                                                  
                                                    }  
                                                  
                                                     
                                                  
                                                    render() {  
                                                  
                                                      return (  
                                                  
                                                        <CustomInput ref={this.callRefInput} />  
                                                  
                                                      );  
                                                  
                                                    }  
                                                  
                                                  }  
                                                  
                                                  export default App;  

                                                    Output

                                                    React Refs

                                                    Callback refs

                                                    In react, there is another way to use refs that is called “callback refs” and it gives more control when the refs are set and unset. Instead of creating refs by createRef() method, React allows a way to create refs by passing a callback function to the ref attribute of a component. It looks like the below code.

                                                    <input type="text" ref={element => this.callRefInput = element} />  

                                                    The callback function is used to store a reference to the DOM node in an instance property and can be accessed elsewhere. It can be accessed as below:

                                                    this.callRefInput.value  

                                                    The example below helps to understand the working of callback refs.

                                                    import React, { Component } from 'react';  
                                                    
                                                    import { render } from 'react-dom';  
                                                    
                                                       
                                                    
                                                    class App extends React.Component {  
                                                    
                                                        constructor(props) {  
                                                    
                                                        super(props);  
                                                    
                                                      
                                                    
                                                        this.callRefInput = null;  
                                                    
                                                      
                                                    
                                                        this.setInputRef = element => {  
                                                    
                                                          this.callRefInput = element;  
                                                    
                                                        };  
                                                    
                                                      
                                                    
                                                        this.focusRefInput = () => {  
                                                    
                                                          //Focus the input using the raw DOM API  
                                                    
                                                          if (this.callRefInput) this.callRefInput.focus();  
                                                    
                                                        };  
                                                    
                                                      }  
                                                    
                                                      
                                                    
                                                      componentDidMount() {  
                                                    
                                                        //autofocus of the input on mount  
                                                    
                                                        this.focusRefInput();  
                                                    
                                                      }  
                                                    
                                                      
                                                    
                                                      render() {  
                                                    
                                                        return (  
                                                    
                                                          <div>  
                                                    
                                                        <h2>Callback Refs Example</h2>  
                                                    
                                                            <input  
                                                    
                                                              type="text"  
                                                    
                                                              ref={this.setInputRef}  
                                                    
                                                            />  
                                                    
                                                            <input  
                                                    
                                                              type="button"  
                                                    
                                                              value="Focus input text"  
                                                    
                                                              onClick={this.focusRefInput}  
                                                    
                                                            />  
                                                    
                                                          </div>  
                                                    
                                                        );  
                                                    
                                                      }  
                                                    
                                                    }  
                                                    
                                                    export default App;  

                                                      In the above example, React will call the “ref” callback to store the reference to the input DOM element when the component mounts, and when the component unmounts, call it with null. Refs are always up-to-date before the componentDidMount or componentDidUpdate fires. The callback refs pass between components is the same as you can work with object refs, which is created with React.createRef().

                                                      Output

                                                      React Refs

                                                      Forwarding Ref from one component to another component

                                                      Ref forwarding is a technique that is used for passing a ref through a component to one of its child components. It can be performed by making use of the React.forwardRef() method. This technique is particularly useful with higher-order components and specially used in reusable component libraries. The most common example is given below.

                                                      Example

                                                      import React, { Component } from 'react';  
                                                      
                                                      import { render } from 'react-dom';  
                                                      
                                                        
                                                      
                                                      const TextInput = React.forwardRef((props, ref) => (  
                                                      
                                                        <input type="text" placeholder="Hello World" ref={ref} />  
                                                      
                                                      ));  
                                                      
                                                        
                                                      
                                                      const inputRef = React.createRef();  
                                                      
                                                        
                                                      
                                                      class CustomTextInput extends React.Component {  
                                                      
                                                        handleSubmit = e => {  
                                                      
                                                          e.preventDefault();  
                                                      
                                                          console.log(inputRef.current.value);  
                                                      
                                                        };  
                                                      
                                                        render() {  
                                                      
                                                          return (  
                                                      
                                                            <div>  
                                                      
                                                              <form onSubmit={e => this.handleSubmit(e)}>  
                                                      
                                                                <TextInput ref={inputRef} />  
                                                      
                                                                <button>Submit</button>  
                                                      
                                                              </form>  
                                                      
                                                            </div>  
                                                      
                                                          );  
                                                      
                                                        }  
                                                      
                                                      }  
                                                      
                                                      export default App;  

                                                        In the above example, there is a component TextInput that has a child as an input field. Now, to pass or forward the ref down to the input, first, create a ref and then pass your ref down to <TextInput ref={inputRef}>. After that, React forwards the ref to the forwardRef function as a second argument. Next, we forward this ref argument down to <input ref={ref}>. Now, the value of the DOM node can be accessed at inputRef.current.

                                                        React with useRef()

                                                        It is introduced in React 16.7 and above version. It helps to get access the DOM node or element, and then we can interact with that DOM node or element such as focussing the input element or accessing the input element value. It returns the ref object whose .current property initialized to the passed argument. The returned object persist for the lifetime of the component.

                                                        Syntax

                                                        const refContainer = useRef(initialValue);  

                                                        Example

                                                        In the below code, useRef is a function that gets assigned to a variable, inputRef, and then attached to an attribute called ref inside the HTML element in which you want to reference.

                                                        function useRefExample() {  
                                                        
                                                          const inputRef= useRef(null);  
                                                        
                                                          const onButtonClick = () => {  
                                                        
                                                            inputRef.current.focus();  
                                                        
                                                          };  
                                                        
                                                          return (  
                                                        
                                                            <>  
                                                        
                                                              <input ref={inputRef} type="text" />  
                                                        
                                                              <button onClick={onButtonClick}>Submit</button>  
                                                        
                                                            </>  
                                                        
                                                          );  
                                                        
                                                        }
                                                      1. Keys

                                                        A key is a unique identifier. In React, it is used to identify which items have changed, updated, or deleted from the Lists. It is useful when we dynamically created components or when the users alter the lists. It also helps to determine which components in a collection needs to be re-rendered instead of re-rendering the entire set of components every time.

                                                        Keys should be given inside the array to give the elements a stable identity. The best way to pick a key as a string that uniquely identifies the items in the list. It can be understood with the below example.

                                                        Example

                                                        const stringLists = [ 'Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa' ];   
                                                        
                                                            
                                                        
                                                        const updatedLists = stringLists.map((strList)=>{   
                                                        
                                                            <li key={strList.id}> {strList} </li>;   
                                                        
                                                        });   

                                                          If there are no stable IDs for rendered items, you can assign the item index as a key to the lists. It can be shown in the below example.

                                                          Example

                                                          const stringLists = [ 'Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa' ];   
                                                          
                                                              
                                                          
                                                          const updatedLists = stringLists.map((strList, index)=>{   
                                                          
                                                              <li key={index}> {strList} </li>;   
                                                          
                                                          });  

                                                            Note: It is not recommended to use indexes for keys if the order of the item may change in future. It creates confusion for the developer and may cause issues with the component state.

                                                            Using Keys with component

                                                            Consider you have created a separate component for ListItem and extracting ListItem from that component. In this case, you should have to assign keys on the <ListItem /> elements in the array, not to the <li> elements in the ListItem itself. To avoid mistakes, you have to keep in mind that keys only make sense in the context of the surrounding array. So, anything you are returning from map() function is recommended to be assigned a key.

                                                            Example: Incorrect Key usage

                                                              import React from 'react';   
                                                            
                                                            import ReactDOM from 'react-dom';   
                                                            
                                                              
                                                            
                                                            function ListItem(props) {  
                                                            
                                                              const item = props.item;  
                                                            
                                                              return (  
                                                            
                                                                // Wrong! No need to specify the key here.  
                                                            
                                                                <li key={item.toString()}>  
                                                            
                                                                  {item}  
                                                            
                                                                </li>  
                                                            
                                                              );  
                                                            
                                                            }  
                                                            
                                                            function NameList(props) {  
                                                            
                                                              const myLists = props.myLists;  
                                                            
                                                              const listItems = myLists.map((strLists) =>  
                                                            
                                                                // The key should have been specified here.  
                                                            
                                                                <ListItem item={strLists} />  
                                                            
                                                              );  
                                                            
                                                              return (  
                                                            
                                                                <div>  
                                                            
                                                                    <h2>Incorrect Key Usage Example</h2>  
                                                            
                                                                          <ol>{listItems}</ol>  
                                                            
                                                                </div>  
                                                            
                                                              );  
                                                            
                                                            }  
                                                            
                                                            const myLists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa'];  
                                                            
                                                            ReactDOM.render(  
                                                            
                                                              <NameList myLists={myLists}/>,  
                                                            
                                                              document.getElementById('app')  
                                                            
                                                            );  
                                                            
                                                            export default App;

                                                              In the given example, the list is rendered successfully. But it is not a good practice that we had not assigned a key to the map() iterator.

                                                              Output

                                                              React Keys

                                                              Example: Correct Key usage

                                                              To correct the above example, we should have to assign key to the map() iterator.

                                                              import React from 'react';   
                                                              
                                                              import ReactDOM from 'react-dom';   
                                                              
                                                                
                                                              
                                                              function ListItem(props) {  
                                                              
                                                                const item = props.item;  
                                                              
                                                                return (  
                                                              
                                                                  // No need to specify the key here.  
                                                              
                                                                  <li> {item} </li>  
                                                              
                                                                );  
                                                              
                                                              }  
                                                              
                                                              function NameList(props) {  
                                                              
                                                                const myLists = props.myLists;  
                                                              
                                                                const listItems = myLists.map((strLists) =>  
                                                              
                                                                  // The key should have been specified here.  
                                                              
                                                                  <ListItem key={myLists.toString()} item={strLists} />  
                                                              
                                                                );  
                                                              
                                                                return (  
                                                              
                                                                  <div>  
                                                              
                                                                      <h2>Correct Key Usage Example</h2>  
                                                              
                                                                          <ol>{listItems}</ol>  
                                                              
                                                                  </div>  
                                                              
                                                                );  
                                                              
                                                              }  
                                                              
                                                              const myLists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa'];  
                                                              
                                                              ReactDOM.render(  
                                                              
                                                                <NameList myLists={myLists}/>,  
                                                              
                                                                document.getElementById('app')  
                                                              
                                                              );  
                                                              
                                                              export default App;

                                                              Output

                                                              React Keys

                                                              Uniqueness of Keys among Siblings

                                                              We had discussed that keys assignment in arrays must be unique among their siblings. However, it doesn’t mean that the keys should be globally unique. We can use the same set of keys in producing two different arrays. It can be understood in the below example.

                                                              Example

                                                              import React from 'react';   
                                                              
                                                              import ReactDOM from 'react-dom';   
                                                              
                                                              function MenuBlog(props) {  
                                                              
                                                                const titlebar = (  
                                                              
                                                                  <ol>  
                                                              
                                                                    {props.data.map((show) =>  
                                                              
                                                                      <li key={show.id}>  
                                                              
                                                                        {show.title}  
                                                              
                                                                      </li>  
                                                              
                                                                    )}  
                                                              
                                                                  </ol>  
                                                              
                                                                );  
                                                              
                                                                const content = props.data.map((show) =>  
                                                              
                                                                  <div key={show.id}>  
                                                              
                                                                    <h3>{show.title}: {show.content}</h3>      
                                                              
                                                                  </div>  
                                                              
                                                                );  
                                                              
                                                                return (  
                                                              
                                                                  <div>  
                                                              
                                                                    {titlebar}  
                                                              
                                                                    <hr />  
                                                              
                                                                    {content}  
                                                              
                                                                  </div>  
                                                              
                                                                );  
                                                              
                                                              }  
                                                              
                                                              const data = [  
                                                              
                                                                {id: 1, title: 'First', content: 'Welcome to JavaTpoint!!'},  
                                                              
                                                                {id: 2, title: 'Second', content: 'It is the best ReactJS Tutorial!!'},  
                                                              
                                                                {id: 3, title: 'Third', content: 'Here, you can learn all the ReactJS topics!!'}  
                                                              
                                                              ];  
                                                              
                                                              ReactDOM.render(  
                                                              
                                                                <MenuBlog data={data} />,  
                                                              
                                                                document.getElementById('app')  
                                                              
                                                              );  
                                                              
                                                              export default App;

                                                              Output

                                                              React Keys
                                                            1. Lists

                                                              Lists are used to display data in an ordered format and mainly used to display menus on websites. In React, Lists can be created in a similar way as we create lists in JavaScript. Let us see how we transform Lists in regular JavaScript.

                                                              The map() function is used for traversing the lists. In the below example, the map() function takes an array of numbers and multiply their values with 5. We assign the new array returned by map() to the variable multiplyNums and log it.

                                                              Example

                                                              var numbers = [1, 2, 3, 4, 5];   
                                                              
                                                              const multiplyNums = numbers.map((number)=>{   
                                                              
                                                                  return (number * 5);   
                                                              
                                                              });   
                                                              
                                                              console.log(multiplyNums);   

                                                                Output

                                                                The above JavaScript code will log the output on the console. The output of the code is given below.

                                                                [5, 10, 15, 20, 25]
                                                                

                                                                Now, let us see how we create a list in React. To do this, we will use the map() function for traversing the list element, and for updates, we enclosed them between curly braces {}. Finally, we assign the array elements to listItems. Now, include this new list inside <ul> </ul> elements and render it to the DOM.

                                                                Example 

                                                                import React from 'react';   
                                                                
                                                                import ReactDOM from 'react-dom';   
                                                                
                                                                  
                                                                
                                                                const myList = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa'];   
                                                                
                                                                const listItems = myList.map((myList)=>{   
                                                                
                                                                    return <li>{myList}</li>;   
                                                                
                                                                });   
                                                                
                                                                ReactDOM.render(   
                                                                
                                                                    <ul> {listItems} </ul>,   
                                                                
                                                                    document.getElementById('app')   
                                                                
                                                                );   
                                                                
                                                                export default App;

                                                                    Output

                                                                    React Lists

                                                                    Rendering Lists inside components

                                                                    In the previous example, we had directly rendered the list to the DOM. But it is not a good practice to render lists in React. In React, we had already seen that everything is built as individual components. Hence, we would need to render lists inside a component. We can understand it in the following code.

                                                                    Example

                                                                    import React from 'react';   
                                                                    
                                                                    import ReactDOM from 'react-dom';   
                                                                    
                                                                      
                                                                    
                                                                    function NameList(props) {  
                                                                    
                                                                      const myLists = props.myLists;  
                                                                    
                                                                      const listItems = myLists.map((myList) =>  
                                                                    
                                                                        <li>{myList}</li>  
                                                                    
                                                                      );  
                                                                    
                                                                      return (  
                                                                    
                                                                        <div>  
                                                                    
                                                                            <h2>Rendering Lists inside component</h2>  
                                                                    
                                                                                  <ul>{listItems}</ul>  
                                                                    
                                                                        </div>  
                                                                    
                                                                      );  
                                                                    
                                                                    }  
                                                                    
                                                                    const myLists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa'];   
                                                                    
                                                                    ReactDOM.render(  
                                                                    
                                                                      <NameList myLists={myLists} />,  
                                                                    
                                                                      document.getElementById('app')  
                                                                    
                                                                    );  
                                                                    
                                                                    export default App;  

                                                                      Output

                                                                      React Lists