Category: Tutorials

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQyRcKIq3ZLxA9Zg6mrPJbmzdvZksYWe4sHpQ&s

  • Table

    A table is an arrangement which organizes information into rows and columns. It is used to store and display data in a structured format.

    The react-table is a lightweight, fast, fully customizable (JSX, templates, state, styles, callbacks), and extendable Datagrid built for React. It is fully controllable via optional props and callbacks.

    Features

    1. It is lightweight at 11kb (and only need 2kb more for styles).
    2. It is fully customizable (JSX, templates, state, styles, callbacks).
    3. It is fully controllable via optional props and callbacks.
    4. It has client-side & Server-side pagination.
    5. It has filters.
    6. Pivoting & Aggregation
    7. Minimal design & easily themeable

    Installation

    Let us create a React app using the following command.

    $ npx create-react-app myreactapp  

    Next, we need to install react-table. We can install react-table via npm command, which is given below.

    $ npm install react-table  

    Once, we have installed react-table, we need to import the react-table into the react component. To do this, open the src/App.js file and add the following snippet.

    import ReactTable from "react-table";  

    Let us assume we have data which needs to be rendered using react-table.

    const data = [{  
    
            name: 'Ayaan',  
    
            age: 26  
    
            },{  
    
            name: 'Ahana',  
    
            age: 22  
    
            },{  
    
            name: 'Peter',  
    
            age: 40   
    
            },{  
    
            name: 'Virat',  
    
            age: 30  
    
            },{  
    
            name: 'Rohit',  
    
            age: 32  
    
            },{  
    
            name: 'Dhoni',  
    
            age: 37  
    
            }] 

      Along with data, we also need to specify the column info with column attributes.

      const columns = [{  
      
             Header: 'Name',  
      
             accessor: 'name'  
      
            },{  
      
            Header: 'Age',  
      
            accessor: 'age'  
      
            }] 

        Inside the render method, we need to bind this data with react-table and then returns the react-table.

        return (  
        
             <div>  
        
                <ReactTable  
        
                    data={data}  
        
                    columns={columns}  
        
                    defaultPageSize = {2}  
        
                    pageSizeOptions = {[2,4, 6]}  
        
                 />  
        
             </div>        
        
        ) 

          Now, our src/App.js file looks like as below.

          import React, { Component } from 'react';  
          
          import ReactTable from "react-table";  
          
          import "react-table/react-table.css";  
          
            
          
          class App extends Component {  
          
            render() {  
          
               const data = [{  
          
                  name: 'Ayaan',  
          
                  age: 26  
          
                  },{  
          
                   name: 'Ahana',  
          
                   age: 22  
          
                   },{  
          
                   name: 'Peter',  
          
                   age: 40      
          
                   },{  
          
                   name: 'Virat',  
          
                   age: 30  
          
                   },{  
          
                   name: 'Rohit',  
          
                   age: 32  
          
                   },{  
          
                   name: 'Dhoni',  
          
                   age: 37  
          
                   }]  
          
               const columns = [{  
          
                 Header: 'Name',  
          
                 accessor: 'name'  
          
                 },{  
          
                 Header: 'Age',  
          
                 accessor: 'age'  
          
                 }]  
          
              return (  
          
                    <div>  
          
                        <ReactTable  
          
                            data={data}  
          
                            columns={columns}  
          
                            defaultPageSize = {2}  
          
                            pageSizeOptions = {[2,4, 6]}  
          
                        />  
          
                    </div>        
          
              )  
          
            }  
          
          }  
          
          export default App; 

            Output

            When we execute the React app, we will get the output as below.

            React Table

            Now, change the rows dropdown menu, we will get the output as below.

            React Table
          1. Map

            A map is a data collection type where data is stored in the form of pairs. It contains a unique key. The value stored in the map must be mapped to the key. We cannot store a duplicate pair in the map(). It is because of the uniqueness of each stored key. It is mainly used for fast searching and looking up data.

            In React, the ?map? method used to traverse and display a list of similar objects of a component. A map is not the feature of React. Instead, it is the standard JavaScript function that could be called on any array. The map() method creates a new array by calling a provided function on every element in the calling array.

            Example

            In the given example, the map() function takes an array of numbers and double their values. We assign the new array returned by map() to the variable doubleValue and log it.

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

              In React, the map() method used for:

              1. Traversing the list element.

              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>React Map Example</h2>  
              
                            <ul>{listItems}</ul>  
              
                  </div>  
              
                );  
              
              }  
              
              const myLists = ['A', 'B', 'C', 'D', 'D'];   
              
              ReactDOM.render(  
              
                <NameList myLists={myLists} />,  
              
                document.getElementById('app')  
              
              );  
              
              export default App;

                

                Output

                React Map

                2. Traversing the list element with keys.

                Example

                import React from 'react';   
                
                import ReactDOM from 'react-dom';   
                
                  
                
                function ListItem(props) {  
                
                  return <li>{props.value}</li>;  
                
                }  
                
                  
                
                function NumberList(props) {  
                
                  const numbers = props.numbers;  
                
                  const listItems = numbers.map((number) =>  
                
                    <ListItem key={number.toString()}  
                
                              value={number} />  
                
                  );  
                
                  return (  
                
                    <div>  
                
                      <h2>React Map Example</h2>  
                
                          <ul> {listItems} </ul>  
                
                    </div>  
                
                  );  
                
                }  
                
                  
                
                const numbers = [1, 2, 3, 4, 5];  
                
                ReactDOM.render(  
                
                  <NumberList numbers={numbers} />,  
                
                  document.getElementById('app')  
                
                );  
                
                export default App;  

                  Output

                  React Map
                1. Bootstrap

                  Single-page applications gaining popularity over the last few years, so many front-end frameworks have introduced such as Angular, React, Vue.js, Ember, etc. As a result, jQuery is not a necessary requirement for building web apps. Today, React has the most used JavaScript framework for building web applications, and Bootstrap become the most popular CSS framework. So, it is necessary to learn various ways in which Bootstrap can be used in React apps, which is the main aim of this section.

                  Adding Bootstrap for React

                  We can add Bootstrap to the React app in several ways. The three most common ways are given below:

                  1. Using the Bootstrap CDN
                  2. Bootstrap as Dependency
                  3. React Bootstrap Package
                  React Bootstrap

                  Using the Bootstrap CDN

                  It is the easiest way of adding Bootstrap to the React app. There is no need to install or download Bootstrap. We can simply put an <link> into the <head> section of the index.html file of the React app as shown in the following snippet.

                  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">  

                  If there is a need to use Bootstrap components which depend on JavaScript/jQuery in the React application, we need to include jQueryPopper.js, and Bootstrap.js in the document. Add the following imports in the <script> tags near the end of the closing </body> tag of the index.html file.

                  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>  
                  
                    
                  
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>  
                  
                    
                  
                  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> 

                    In the above snippet, we have used jQuery’s slim version, although we can also use the full version as well. Now, Bootstrap is successfully added in the React application, and we can use all the CSS utilities and UI components available from Bootstrap in the React application.

                    Bootstrap as Dependency

                    If we are using a build tool or a module bundler such as Webpack, then importing Bootstrap as dependency is the preferred option for adding Bootstrap to the React application. We can install Bootstrap as a dependency for the React app. To install the Bootstrap, run the following commands in the terminal window.

                    $ npm install bootstrap --save  

                    Once Bootstrap is installed, we can import it in the React application entry file. If the React project created using the create-react-app tool, open the src/index.js file, and add the following code:

                    import 'bootstrap/dist/css/bootstrap.min.css';  

                    Now, we can use the CSS classes and utilities in the React application. Also, if we want to use the JavaScript components, we need to install the jquery and popper.js packages from npm. To install the following packages, run the following command in the terminal window.

                    $ npm install jquery popper.js  

                    Next, go to the src/index.js file and add the following imports.

                    import $ from 'jquery';  
                    
                    import Popper from 'popper.js';  
                    
                    import 'bootstrap/dist/js/bootstrap.bundle.min';

                    Now, we can use Bootstrap JavaScript Components in the React application.

                    React Bootstrap Package

                    The React Bootstrap package is the most popular way to add bootstrap in the React application. There are many Bootstrap packages built by the community, which aim to rebuild Bootstrap components as React components. The two most popular Bootstrap packages are:

                    1. react-bootstrap: It is a complete re-implementation of the Bootstrap components as React components. It does not need any dependencies like bootstrap.js or jQuery. If the React setup and React-Bootstrap installed, we have everything which we need.
                    2. reactstrap: It is a library which contains React Bootstrap 4 components that favor composition and control. It does not depend on jQuery or Bootstrap JavaScript. However, react-popper is needed for advanced positioning of content such as Tooltips, Popovers, and auto-flipping Dropdowns.

                    React Bootstrap Installation

                    Let us create a new React app using the create-react-app command as follows.

                    $ npx create-react-app react-bootstrap-app  

                    After creating the React app, the best way to install Bootstrap is via the npm package. To install Bootstrap, navigate to the React app folder, and run the following command.

                    $ npm install react-bootstrap bootstrap --save  

                    Importing Bootstrap

                    Now, open the src/index.js file and add the following code to import the Bootstrap file.

                    import 'bootstrap/dist/css/bootstrap.min.css';  

                    We can also import individual components like import { SplitButton, Dropdown } from ‘react-bootstrap’; instead of the entire library. It provides the specific components which we need to use, and can significantly reduce the amount of code.

                    In the React app, create a new file named ThemeSwitcher.js in the src directory and put the following code.

                    import React, { Component } from 'react';  
                    
                    import { SplitButton, Dropdown } from 'react-bootstrap';  
                    
                      
                    
                    class ThemeSwitcher extends Component {  
                    
                      
                    
                      state = { theme: null }  
                    
                        
                    
                      chooseTheme = (theme, evt) => {  
                    
                        evt.preventDefault();  
                    
                        if (theme.toLowerCase() === 'reset') { theme = null }  
                    
                        this.setState({ theme });  
                    
                      }  
                    
                        
                    
                      render() {  
                    
                        const { theme } = this.state;  
                    
                        const themeClass = theme ? theme.toLowerCase() : 'default';  
                    
                          
                    
                        const parentContainerStyles = {  
                    
                          position: 'absolute',  
                    
                          height: '100%',  
                    
                          width: '100%',  
                    
                          display: 'table'  
                    
                        };  
                    
                          
                    
                        const subContainerStyles = {  
                    
                          position: 'relative',  
                    
                          height: '100%',  
                    
                          width: '100%',  
                    
                          display: 'table-cell',  
                    
                        };  
                    
                          
                    
                        return (  
                    
                          <div style={parentContainerStyles}>  
                    
                            <div style={subContainerStyles}>  
                    
                              
                    
                              <span className={h1 center-block text-center text-${theme ? themeClass : 'muted'}} style={{ marginBottom: 25 }}>{theme || 'Default'}</span>  
                    
                                
                    
                              <div className="center-block text-center">  
                    
                                <SplitButton bsSize="large" bsStyle={themeClass} title={${theme || 'Default Block'} Theme}>  
                    
                                  <Dropdown.Item eventKey="Primary Block" onSelect={this.chooseTheme}>Primary Theme</Dropdown.Item>  
                    
                                  <Dropdown.Item eventKey="Danger Block" onSelect={this.chooseTheme}>Danger Theme</Dropdown.Item>  
                    
                                  <Dropdown.Item eventKey="Success Block" onSelect={this.chooseTheme}>Success Theme</Dropdown.Item>  
                    
                                  <Dropdown.Item divider />  
                    
                                  <Dropdown.Item eventKey="Reset Block" onSelect={this.chooseTheme}>Default Theme</Dropdown.Item>  
                    
                                </SplitButton>  
                    
                              </div>    
                    
                            </div>  
                    
                          </div>  
                    
                        );   
                    
                      }   
                    
                    }  
                    
                    export default ThemeSwitcher; 

                      Now, update the src/index.js file with the following snippet.

                      Index.js

                      import 'bootstrap/dist/css/bootstrap.min.css';  
                      
                      import React from 'react';  
                      
                      import ReactDOM from 'react-dom';  
                      
                      import App from './App.js';  
                      
                      import './index.css';  
                      
                      import ThemeSwitcher from './ThemeSwitcher';  
                      
                        
                      
                      ReactDOM.render(<ThemeSwitcher />, document.getElementById('root')); 

                        Output

                        When we execute the React app, we should get the output as below.

                        React Bootstrap

                        Click on the dropdown menu. We will get the following screen.

                        React Bootstrap

                        Now, if we choose the Success Theme, we will get the below screen.

                        React Bootstrap

                        Using reactstrap

                        Let us create a new React app using the create-react-app command as follows.

                        $ npx create-react-app reactstrap-app  

                        Next, install the reactstrap via the npm package. To install reactstrap, navigate to the React app folder, and run the following command.

                        $ npm install bootstrap reactstrap --save  

                        Importing Bootstrap

                        Now, open the src/index.js file and add the following code to import the Bootstrap file.

                        import 'bootstrap/dist/css/bootstrap.min.css';  

                        We can also import individual components like import { Button, Dropdown } from ‘reactstrap’; instead of the entire library. It provides the specific components which we need to use, and can significantly reduce the amount of code.

                        In the React app, create a new file named ThemeSwitcher.js in the src directory and put the following code.

                        import React, { Component } from 'react';  
                        
                        import { Button, ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';  
                        
                          
                        
                        class ThemeSwitcher extends Component {  
                        
                          
                        
                          state = { theme: null, dropdownOpen: false }  
                        
                            
                        
                          toggleDropdown = () => {  
                        
                            this.setState({ dropdownOpen: !this.state.dropdownOpen });  
                        
                          }  
                        
                            
                        
                          resetTheme = evt => {  
                        
                            evt.preventDefault();  
                        
                            this.setState({ theme: null });  
                        
                          }  
                        
                            
                        
                          chooseTheme = (theme, evt) => {  
                        
                            evt.preventDefault();  
                        
                            this.setState({ theme });  
                        
                          }  
                        
                          render() {  
                        
                            const { theme, dropdownOpen } = this.state;  
                        
                            const themeClass = theme ? theme.toLowerCase() : 'secondary';  
                        
                              
                        
                            return (  
                        
                              <div className="d-flex flex-wrap justify-content-center align-items-center">  
                        
                                
                        
                                <span className={h1 mb-4 w-100 text-center text-${themeClass}}>{theme || 'Default'}</span>  
                        
                                  
                        
                                <ButtonDropdown isOpen={dropdownOpen} toggle={this.toggleDropdown}>  
                        
                                  <Button id="caret" color={themeClass}>{theme || 'Custom'} Theme</Button>  
                        
                                  <DropdownToggle caret size="lg" color={themeClass} />  
                        
                                  <DropdownMenu>  
                        
                                    <DropdownItem onClick={e => this.chooseTheme('Primary', e)}>Primary Theme</DropdownItem>  
                        
                                    <DropdownItem onClick={e => this.chooseTheme('Danger', e)}>Danger Theme</DropdownItem>  
                        
                                    <DropdownItem onClick={e => this.chooseTheme('Success', e)}>Success Theme</DropdownItem>  
                        
                                    <DropdownItem divider />  
                        
                                    <DropdownItem onClick={this.resetTheme}>Default Theme</DropdownItem>  
                        
                                  </DropdownMenu>  
                        
                                </ButtonDropdown>  
                        
                                  
                        
                              </div>  
                        
                            );    
                        
                          }  
                        
                        }  
                        
                        export default ThemeSwitcher;  

                          Now, update the src/index.js file with the following snippet.

                          Index.js

                          import 'bootstrap/dist/css/bootstrap.min.css';  
                          
                          import React from 'react';  
                          
                          import ReactDOM from 'react-dom';  
                          
                          import App from './App.js';  
                          
                          import './index.css';  
                          
                          import ThemeSwitcher from './ThemeSwitcher';  
                          
                            
                          
                          ReactDOM.render(<ThemeSwitcher />, document.getElementById('root'));  

                            Output

                            When we execute the React app, we should get the output as below.

                            React Bootstrap

                            Click on the dropdown menu. We will get the following screen.

                            React Bootstrap

                            Now, if we choose the Danger Theme, we will get the below screen.

                            React Bootstrap
                          1. Animation

                            The animation is a technique in which images are manipulated to appear as moving images. It is one of the most used technique to make an interactive web application. In React, we can add animation using an explicit group of components known as the React Transition Group.

                            React Transition Group is an add-on component for managing component states and useful for defining entering and exiting transitions. It is not able to animate styles by itself. Instead, it exposes transition states, manages classes and group elements, and manipulates the DOM in useful ways. It makes the implementation of visual transitions much easier.

                            React Transition group has mainly two APIs to create transitions. These are:

                            1. ReactTransitionGroup: It uses as a low-level API for animation.
                            2. ReactCSSTransitionGroup: It uses as a high-level API for implementing basic CSS transitions and animations.

                            Installation

                            We need to install react-transition-group for creating animation in React Web application. You can use the below command.

                            $ npm install react-transition-group --save  

                            React Transition Group Components

                            React Transition Group API provides three main components. These are:

                            1. Transition
                            2. CSSTransition
                            3. Transition Group

                            Transition

                            It has a simple component API to describe a transition from one component state to another over time. It is mainly used to animate the mounting and unmounting of a component. It can also be used for in-place transition states as well.

                            We can access the Transition component into four states:

                            • entering
                            • entered
                            • exiting
                            • exited

                            CSSTransition

                            The CSSTransition component uses CSS stylesheet classes to write the transition and create animations. It is inspired by the ng-animate library. It can also inherit all the props of the transition component. We can divide the “CSSTransition” into three states. These are:

                            • Appear
                            • Enter
                            • Exit

                            CSSTransition component must be applied in a pair of class names to the child components. The first class is in the form of name-stage and the second class is in the name-stage-active. For example, you provide the name fade, and when it applies to the ‘enter’ stage, the two classes will be fade-enter and fade-enter-active. It may also take a prop as Timeout which defines the maximum time to animate.

                            TransitionGroup

                            This component is used to manage a set of transition components (Transition and CSSTransition) in a list. It is a state machine that controls the mounting and unmounting of components over time. The Transition component does not define any animation directly. Here, how ‘list’ item animates is based on the individual transition component. It means, the “TransitionGroup” component can have different animation within a component.

                            Let us see the example below, which clearly help to understand the React Animation.

                            Example

                            App.js

                            In the App.js file, import react-transition-group component, and create the CSSTransition component that uses as a wrapper of the component you want to animate. We are going to use transitionEnterTimeout and transitionLeaveTimeout for CSS Transition. The Enter and Leave animations used when we want to insert or delete elements from the list.

                            import React, { Component } from 'react';  
                            
                            import { CSSTransitionGroup } from 'react-transition-group';  
                            
                              
                            
                            class App extends React.Component {  
                            
                                constructor(props) {  
                            
                                super(props);  
                            
                                this.state = {items: ['Blockchain', 'ReactJS', 'TypeScript', 'JavaTpoint']};  
                            
                                this.handleAdd = this.handleAdd.bind(this);  
                            
                              }  
                            
                              
                            
                              handleAdd() {  
                            
                                const newItems = this.state.items.concat([  
                            
                                  prompt('Enter Item Name')  
                            
                                ]);  
                            
                                this.setState({items: newItems});  
                            
                              }  
                            
                              
                            
                              handleRemove(i) {  
                            
                                let newItems = this.state.items.slice();  
                            
                                newItems.splice(i, 1);  
                            
                                this.setState({items: newItems});  
                            
                              }  
                            
                              
                            
                              render() {  
                            
                                const items = this.state.items.map((item, i) => (  
                            
                                  <div key={item} onClick={() => this.handleRemove(i)}>  
                            
                                    {item}  
                            
                                  </div>  
                            
                                ));  
                            
                              
                            
                                return (  
                            
                                  <div>  
                            
                                <h1>Animation Example</h1>  
                            
                                        <button onClick={this.handleAdd}>Insert Item</button>  
                            
                                        <CSSTransitionGroup  
                            
                                           transitionName="example"  
                            
                                       transitionEnterTimeout={800}  
                            
                                           transitionLeaveTimeout={600}>  
                            
                                           {items}  
                            
                                        </CSSTransitionGroup>  
                            
                                  </div>  
                            
                                );  
                            
                              }  
                            
                            }  
                            
                            export default App;  

                              Main.js

                              import React from 'react';  
                              
                              import ReactDOM from 'react-dom';  
                              
                              import App from './App.js';  
                              
                                
                              
                              ReactDOM.render(<App />, document.getElementById('app'));

                              style.css

                              Add style.css file in your application, and add the following CSS styles. Now, to use this CSS file, you need to add the link of this file in your HTML file.

                              .example-enter {  
                              
                                opacity: 0.01;  
                              
                              }  
                              
                                
                              
                              .example-enter.example-enter-active {  
                              
                                opacity: 1;  
                              
                                transition: opacity 500ms ease-in;  
                              
                              }  
                              
                                
                              
                              .example-leave {  
                              
                                opacity: 1;  
                              
                              }  
                              
                                
                              
                              .example-leave.example-leave-active {  
                              
                                opacity: 0.01;  
                              
                                transition: opacity 300ms ease-in;  
                              
                              }

                                In the above example, the animation durations are specified in both the CSS and render method. It tells React component when to remove the animation classes from the list and if it is leaving when to remove the element from the DOM.

                                Output

                                When we execute the above program, it gives the below output.

                                React Animation

                                Click on ‘Insert Item‘ button, the following screen appears.

                                React Animation

                                Once we insert the item and press Ok, the new item can be added in the list with fade in style. Here, we can also delete any item from the list by clicking on the particular link.

                                React Animation
                              1. 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. 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