web-development top banner

How to Work with Lists in React.Js

Read it in 15 Mins

Last updated on
07th Jun, 2022
Published
25th May, 2021
Views
5,688
How to Work with Lists in React.Js

React is a JavaScript library designed for developing quick and interactive user interfaces for web and mobile applications. It is an open-source, component-based, front-end library accountable only for the application's view layer. In Model View Controller (MVC) architecture, the view layer is liable for the app's looks and feel. React was founded by Jordan Walke, a software engineer at Facebook. To have a deeper understanding on usereducer in React, click here. 

Why has React gained popularity?

React's fame today has overshadowed that of all other front-end development frameworks. Here is why:

1. Simple creation of powerful and dynamic applications:

React makes it more comfortable to create powerful and dynamic web applications because it demands less coding and contributes more functionality than JavaScript, where coding often gets complex instantly.

2. Enhanced performance: 

React utilizes Virtual DOM, thereby creating web applications quicker. Virtual DOM matches the components' previous states and updates only the Real DOM items that were modified, instead of refreshing all of the features again, as traditional web applications do 

3. Reusable segments: 

Components are the building blocks of any React application, and a single app typically consists of various ingredients. These segments possess their philosophy and controls, and they can be reused everywhere in the application, which in turn dramatically lessens the application's evolution time. 

4. Unidirectional information flow: 

React accompanies a unidirectional data flow. This means that when creating a React app, developers often nest child components within parent components. Since the data moves in a single direction, it becomes simpler to debug errors and understand where an obstacle occurs in an application at the moment in question. 

5. Light learning curve: 

React is simple to learn, as it primarily combines basic HTML and JavaScript concepts with remarkable helpful additions. Still, as is the problem with other tools and frameworks, you have to spend some time to get a decent understanding of React's library. 

6. Develop web and mobile apps: 

We already know that React is utilized to build web applications, but that's not the only thing it can do. There is a framework named React Native, procured from React itself, that is hugely successful and is employed for creating mobile applications. So, in truth, React can be utilized for making both web and mobile applications. 

7. Dedicated tools for smooth debugging: 

Facebook has delivered a Chrome extension that can be utilized to debug React applications. This allows quicker and easier ways of debugging React web applications. 

The earlier reasons support the React library's reputation, and it is being utilized by many organizations and businesses. 

Introduction to ‘key’ attribute and its importance 

  • Keys support React to identify which items have been modified, are combined, or are eliminated. Keys should be assigned to the elements inside the array to provide the elements with a steady identity. 
  • React keys are essential when working with dynamically created components or when your lists are altered by users. 
  • Setting the key value will keep components unique, later after the conversion. 

Using Keys

  • Let's dynamically generate Content elements with a unique index(i). 
  • The mapfunction() will generate three elements from our data array. Since the key-value needs to be unique for every aspect, we will assign i as a key for each built element. 
import React from 'react'; 
import ReactDOM from 'react-dom'; 
class App extends React.Component { 
   constructor() { 
      super(); 
 
      this.state = { 
         data:  
         [ 
            { 
               component: 'The first element generated', 
               id: 7 
            }, 
            { 
               component: 'The second element generated', 
               id: 8 
            }, 
            { 
               component: 'The third element generated, 
               id: 9 
            } 
         ] 
      } 
   } 
   render() { 
      return ( 
         <div> 
            <div> 
               {this.state.data.map((dynamicComponent, i) = <Content  
                  key = {i} componentData = {dynamicComponent}/>)} 
            </div> 
         </div> 
      ); 
   } 
} 
class Content extends React.Component { 
   render() { 
      return ( 
         <div> 
            <div>{this.props.componentData.component}</div> 
            <div>{this.props.componentData.id}</div> 
         </div> 
      ); 
   } 
} 
ReactDOM.render(<App/>, document.getElementById('app'))

Output 

 component: 'The first element generated', 
 id: 7 
 component: 'The second element generated', 
 id: 8 
 component: 'The third element generated, 
 id: 9 

Lists are everywhere 

Lists are handy when it comes to developing the UI of any website. Lists are mainly used for displaying menus on a website, for example, the navbar menu. In conventional JavaScript, we can use arrays for creating lists. We can produce lists in React in a similar manner as we do in standard JavaScript. 

Creating a list of elements in React

Let us now generate a list in React. Render the list in the below code as an unordered list in the browser rather than only logging in to the console. We will traverse the list using the JavaScript map() function and update elements to be embedded between <li> </li> elements. Finally we will enclose this new list within <ul> </ul> elements and render it to the DOM. 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
const numbers = [2,3,4,5,6]; 
const updatedNums = numbers.map((number)=>{ 
    return <li>{number}</li>; 
}); 
ReactDOM.render( 
    <ul> 
        {updatedNums} 
    </ul>,  
    document.getElementById('root') 
); 

The above code will be shown list as below  

2 
3 
4 
5 
6 

1. react native flatlist: 
This is a convenient react utility component designed to simplify handling the rendering list with ease. It can take grouping, sorting, filtering, searching, sorting, paginating, styling with very simple props. 

Instate 

Assure that react and react-dom version 16.8.0+ should be installed 

npm install flatlist-react 

Quick Start 

Take into consideration the following list passed to component PeopleList: 

// App.jsx 
people = [ 
{firstName: 'John', lastName: 'Correia', info: {age: 25}}, 
{firstName: 'Tim, lastName: 'Doe', info: {age: 18}}, 
{firstName: 'Joe', lastName: 'Doe', info: {age: 36}}, 
{firstName: 'Michelle', lastName: 'Carvalho', info: {age: 28}}, 
{firstName: 'Kathy, lastName: 'Correia', info:{age: 29}}, 
{firstName: 'Dave', lastName: 'Quichote', info: {age: 35}}, 
{firstName: 'Maria', lastName: 'Correia', info: {age: 0}}, 
{firstName: 'Brian', lastName: 'Gonzales', info: {age: 85}}, 
{firstName: 'Anna', lastName: 'Correia', info: {age: 34}} 
] 
<PeopleList people={people}/> 

Now inside the component file, a function renderPerson would pass to renderItem:

// PeopleList.jsx 
import FlatList from 'flatlist-react'; 
renderPerson = (person, idx) => { 
return ( 
<li key={idx}> 
<b>{person.firstName} {person.lastName}</b> (<span>{person.info.age}</span>) 
</li> 
); 
} 
return ( 
<ul> 
<FlatList 
list={this.props.people} 
renderItem={this.renderPerson} 
renderWhenEmpty={() => <div>List is empty!</div>} 
sortBy={["firstName", {key: "lastName", descending: true}]} 
groupBy={person => person.info.age > 18 ? 'Over 18' : 'Under 18'} 
/> 
</ul> 
)

2. react dropdownlist

Simple Dropdown inspired by react-select

Why

  • The default HTML select component is hard to style 
  • Fulfills requirement of grouped menus 
  • if Advanced select is required, check react-select

Basic usage of react-dropdown  

import Dropdown from 'react-dropdown'; 
import 'react-dropdown/style.css'; 
const options = [ 
'one', 'two', 'three' 
]; 
const defaultOption = options[0]; 
<Dropdown options={options} onChange={this._onSelect} value={defaultOption} placeholder="Select an option" />;

3. react native list view  

Create a list in React Native. We will import the List in our Home component and show it on screen. 

App.js 
import React from 'react' 
import List from './List.js' 
const App = () => { 
   return ( 
      <List /> 
   ) 
} 
export default App 

Use map() method as this will iterate over various items and render each one. 

List.js 
import React, { Component } from 'react' 
import { Text, View, TouchableOpacityStyleSheet } from 'react-native'  
class List extends Component { 
   state = { 
      names: [ 
         { 
            id: 0, 
            name: 'Ben', 
         }, 
         { 
            id: 1, 
            name: 'Susan', 
         }, 
         { 
            id: 2, 
            name: 'Robert', 
         }, 
         { 
            id: 3, 
            name: 'Mary', 
         } 
      ] 
   } 
   alertItemName = (item) => { 
      alert(item.name) 
   } 
   render() { 
      return ( 
         <View> 
            { 
               this.state.names.map((item, index) => ( 
                  <TouchableOpacity 
                     key = {item.id} 
                     style = {styles.container} 
                     onPress = {() => this.alertItemName(item)}> 
                     <Text style = {styles.text}> 
                        {item.name} 
                     </Text> 
                  </TouchableOpacity> 
               )) 
            } 
         </View> 
      ) 
   } 
} 
export default List 
const styles = StyleSheet.create ({ 
   container: { 
      padding: 10, 
      marginTop: 3, 
      backgroundColor: '#d9f9b1', 
      alignItems: 'center', 
   }, 
   text: { 
      color: '#4f603c' 
   } 
}) 

5. material ui list   

Material-UI is a customizable and straightforward component library to build faster, beautiful, and more accessible React applications. Follow your design system, or start with Material Design.

import './App.css'; 
import {Button} from '@material-ui/core'; //importing material ui component 
function App() { 
 return ( 
<div className="App"> 
<Button> Press me </Button> //using the material ui component in our project 
</div> 
); 
} 
export default App;

 Refresh browser and will see a button with the words press me.

6. react todo list

Create populating todo list items.

import React, { Component } from "react"; 
export default class FormTodo extends Component { 
state = { 
inputValue: "", 
todos: [], 
}; 
inputChange = (e) => { 
this.setState({ 
inputValue: e.target.value, 
}); 
}; 
buttonSubmit = (e) => { 
this.setState({ 
// todos: [this.state.inputValue], 
todos: [this.state.inputValue, ...this.state.todos], 
inputValue: "", // input field clearing on submitting 
}); 
}; 
render() { 
return ( 
<div> 
<input 
type="text" 
value={this.state.inputValue} 
placeholder="Enter task..." 
onChange={this.inputChange} 
/> 
<button onClick={this.buttonSubmit}>Add task</button> 
<ol> 
{this.state.todos.map((todo) => ( 
<li>{todo}</li> 
))} 
</ol> 
</div> 
); 
} 
}

Simple Reactjs List with Simple Array

Display data of a simple array having a list of countries in it. We will use .map to render the item in React. 

import React from "react"; 
 function App() { 
const CustomerName= [ 
{ name: "Ram" }, 
{ name: "Shyam" }, 
{ name: "Mahendra" }, 
{ name: "Vikrant" }, 
{ name: "Ramesh" }, 
{ name: "Mahesh" } 
]; 
return ( 
<ul> 
{CustomerName.map((data) => ( 
<li>{data.name}</li> 
))} 
</ul> 
); 
} 

Display Nested Lists in React

We needed to show data in nested form. 

import React from 'react'; 
function App() { 
const users = [ 
{ 
id: "01", 
name: "John Manchak", 
email: "sincerity@may.biz", 
zipcode: 14112 
}, 
{ 
id: "02", 
name: "Jim Howell", 
email: "Shanni@melissa.com", 
zipcode: 15111 
} 
];  
const finalArray = [users, users]; 
return ( 
<div> 
<ul> 
{finalArray.map((nestedItemi) => ( 
<ul key={i}> 
<h3> List {i} </h3> 
{nestedItem.map(data => ( 
<li key={data.id}> 
<div>{data.name}</div> 
<div>{data.email}</div> 
<div>{data.zipcode}</div> 
</li> 
))} 
</ul> 
))} 
</ul> 
</div> 
); 
} 

Building a collapsible list

We can create a simple collapsible component in react js. We will be passing the heading as a property to the element, and the .jsx that gets wrapped inside the component would be toggled on clicking the header. 

class Collapsible extends React.Component { 
constructor(props){ 
super(props); 
this.state = { 
open: false 
} 
this.togglePanel = this.togglePanel.bind(this); 
} 
togglePanel(e){ 
this.setState({open: !this.state.open}) 
} 
render() { 
return (<div> 
<div onClick={(e)=>this.togglePanel(e)} className=’header’> 
{this.props.title}</div> 
{this.state.open ? ( 
<div className=’content’> 
{this.props.children} 
</div> 
) : null} 
</div>); 
} 
} 
/* CSS */ 
.header{ 
cursor: pointer; 
border: solid 1px #f2f2f2; 
padding: 15px; 
background-color: #0089CC; 
color: #FFF; 
font-family: verdana; 
} 
.content{ 
cursor: pointer; 
border-left: solid 1px #f2f2f2; 
border-right: solid 1px #f2f2f2; 
border-bottom: solid 1px #f2f2f2; 
border-radius: 0 0 5px 5px; 
padding: 15px; 
font-family: verdana; 
font-size: 14px; 
} 

Sorting lists

ReactJs can create sorting lists as below: 

import SortableItemswapArrayPositions } from 'react-sort-list'; 
import useState } from 'react'; 
let todos = [ 
  {id: 1, title: "TaskItem 1"}, 
  {id: 2, title: "TaskItem 2"}, 
  {id: 3, title: "TaskItem 3"} 
] 
function App() { 
  const [todoStatesetTodoState] = useState(todos); 
  function swap(dragIndexdropIndex) { 
    let swappedTodos = swapArrayPositions(todoStatedragIndexdropIndex); 
    setTodoState([...swappedTodos]);     
  } 
  return ( 
  <ul> 
      {todoState.map(function (todo, index) { 
          return ( 
            <SortableItem items={todoState} id={todo.id} key={todo.id} swap={swap} > 
              <li> {todo.title} </li> 
            </SortableItem> 
          ) 
      })} 
    </ul> 
  ); 
} 
export default App;

Inserting / Removing an element from the list

In ReactJs we can add or remove dynamically from the list as below: 

var App = React.createClass({ 
  getInitialState : function() { 
    return ( 
      { 
        fruits : { 
          'fruit-1' : 'orange', 
          'fruit-2' : 'apple' 
        } 
      } 
     ) 
    }, 
    addFruit : function(fruit) { 
      //create a unike key for each new fruit item 
      var timestamp = (new Date()).getTime(); 
      // update the state object 
      this.state.fruits['fruit-' + timestamp ] = fruit; 
      // set the state 
      this.setState({ fruits : this.state.fruits }); 
     }, 
     removeFruit : function(fruitKey) { 
      // update the state object 
      delete this.state.fruits[fruitKey]; 
      // set the state 
      this.setState({ fruits : this.state.fruits }); 
      //alert(fruitKey); 
     }, 
     render: function() { 
      return ( 
        <div className="component-wrapper"> 
          <FruitList fruits={this.state.fruits} /> 
          <AddFruitForm addFruit={this.addFruit} /> 
          <RemoveFruitForm removeFruit={this.removeFruit} fruits={this.state.fruits} /> 
        </div> 
       ); 
      } 
     }); 
     var FruitList = React.createClass({ 
      render : function() { 
        return ( 
          <div className="container"> 
            <ul className="list-group text-center"> 
              { 
                Object.keys(this.props.fruits).map(function(key) { 
                  return <li className="list-group-item list-group-item-info">{this.props.fruits[key]}</li> 
                }.bind(this)) 
              } 
            </ul> 
           </div> 
          ); 
        } 
      }); 
      var AddFruitForm = React.createClass({ 
        createFruit : function(e) { 
          e.preventDefault(); 
          //get the fruit object name from the form 
          var fruit = this.refs.fruitName.value; 
          //call the addFruit method of the App component 
          //to change the state of the fruit list by adding a new item 
          if(fruit.length > 0) { 
            this.props.addFruit(fruit); 
          } 
          //reset the form 
          this.refs.fruitForm.reset(); 
        }, 
        render : function() { 
          return( 
            <form className="form-inline" ref="fruitFormonSubmit={this.createFruit}> 
              <div className="form-group"> 
                <label for="fruitItem"> 
                  Fruit Name 
                  <input type="text" id="fruitItemclassName="form-control" placeholder="e.x.lemmon" ref="fruitName" /> 
                </label> 
              </div> 
              <button type="submit" className="btn btn-primary">Add Fruit</button> 
            </form> 
          ) 
        } 
      }); 
      var RemoveFruitForm = React.createClass({ 
        selectFruittoRemove : function(e) { 
          var fruit = e.target.value; 
          //get the fruit object name from the form 
          //var fruit = this.refs.removeFruitSelect.value; 
          //call the addFruit method of the App component 
          //to change the state of the fruit list by adding a new item 
          this.props.removeFruit(fruit); 
          //reset the form 
          this.refs.removeFruitForm.reset(); 
        }, 
        render : function() { 
          return( 
            <form className="form-inline" ref="removeFruitFormonChange={this.selectFruittoRemove}> 
             <div className="form-group"> 
              <label for="selectFruit"> 
                List of Fruits 
                <select id="selectFruitclassName="form-control"> 
                  <option value="">Remove a fruit</option> 
                  { 
                    Object.keys(this.props.fruits).map(function(key) { 
                      return <option value={key}>{this.props.fruits[key]}</option> 
                    }.bind(this)) 
                  } 
                </select> 
              </label> 
              </div> 
            </form> 
          ) 
        } 
      }); 
      React.render( 
        <App />, 
        document.getElementById('app') 
      ); 

Building a newsfeed component

Essentials

A basic understanding of JavaScript (ES6) and React is required. The following needs to be installed on your machine: 

  • Node.js (v6 and above) 
  • Npm 

Create a new empty directory news-app and run npm init -y from within it to initialize the project with a package.json file.

Set React app 

We will bootstrap our React application with create-react-app.  

command: 

npm install -g create-react-app 

Once the installation process is completed, run the command below to set up your React application: 

create-react-app client 

Install the other dependencies; we will need to build the app frontend. 

npm install pusher-js pushid 

pushid helps us generate a random ID string which we’ll be needing when creating the news feed. Run yarn start to launch the development server once all the dependencies have been installed. 

Application logic

import React, { Component } from 'react'; 
    import Pusher from 'pusher-js'; 
    import pushid from 'pushid'; 
    import './App.css'; 
    class App extends Component { 
      state = { 
        newsItems: [], 
      } 
      componentDidMount() { 
        fetch('http://localhost:5000/live') 
          .then(response => response.json()) 
          .then(articles => { 
            this.setState({ 
              newsItems: [...this.state.newsItems, ...articles], 
            }); 
          }).catch(error => console.log(error)); 
        const pusher = new Pusher('<your app key>', { 
          cluster: '<your app cluster>', 
          encrypted: true, 
        }); 
        const channel = pusher.subscribe('news-channel'); 
        channel.bind('update-news', data => { 
          this.setState({ 
            newsItems: [...data.articles, ...this.state.newsItems], 
          }); 
        }); 
      } 
      render() { 
        const NewsItem = (article, id) => ( 
          <li key={id}><a href={`${article.url}`}>{article.title}</a></li> 
        ); 
       const newsItems = this.state.newsItems.map(e => NewsItem(e, pushid())); 
        return ( 
          <div className="App"> 
            <h1 className="App-title">Live Bitcoin Feed</h1> 
            <ul className="news-items">{newsItems}</ul> 
         </div> 
        ); 
      } 
    } 
    export default App;   
Application styles 
Change its contents to look like this: 
 .App { 
      width: 100%; 
      max-width: 700px; 
      margin: 0 auto; 
    } 
    .App-title { 
      text-align: center; 
    } 
    .text-input { 
      width: 100%; 
      border: 1px solid #f7f7f7; 
      padding: 10px; 
    } 
    .text-input:hover { 
      box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25); 
    } 
    .news-items { 
      list-style: none; 
      padding-left: 0; 
    } 
    .news-items li { 
      margin-bottom: 10px; 
    }

Server Setup 

Let’s install a simplistic Express server to fetch news items from and trigger real-time updates with Pusher. 

npm install express cors dotenv newsapi Pusher --save Create a new server.js file and open it up in your text editor. Add the following code to server.js: 

require('dotenv').config({ path: 'variables.env' }); 
    const express = require('express'); 
    const cors = require('cors'); 
    const Pusher = require('pusher'); 
    const NewsAPI = require('newsapi'); 
    const app = express(); 
    const pusher = new Pusher({ 
      appIdprocess.env.PUSHER_APP_ID, 
      key: process.env.PUSHER_APP_KEY, 
      secret: process.env.PUSHER_APP_SECRET, 
      cluster: process.env.PUSHER_APP_CLUSTER, 
      encrypted: true, 
    }); 
    const newsapi = new NewsAPI(process.env.NEWS_API_KEY); 
    const fetchNews = (searchTermpageNum) => 
      newsapi.v2.everything({ 
        q: searchTerm, 
        language: 'en', 
        page: pageNum, 
        pageSize: 5, 
      }); 
    app.use(cors()); 
    function updateFeed(topic) { 
      let counter = 2; 
      setInterval(() => { 
        fetchNews(topic, counter) 
          .then(response => { 
            pusher.trigger('news-channel', 'update-news', { 
              articles: response.articles, 
            }); 
            counter += 1; 
          }) 
          .catch(error => console.log(error)); 
      }, 5000); 
    } 
    app.get('/live', (req, res) => { 
      const topic = 'bitcoin'; 
      fetchNews(topic, 1) 
        .then(response => { 
          res.json(response.articles); 
          updateFeed(topic); 
        }) 
        .catch(error => console.log(error)); 
    }); 
    app.set('port', process.env.PORT || 5000); 
    const server = app.listen(app.get('port'), () => { 
      console.log(`Express running → PORT ${server.address().port}`); 
    }); 

Once the /live endpoint is connected, news articles about bitcoin are regained from newsapi.org and transmitted back to the client.

Begin the server by running node server.js from the root of your project directory. At this detail, news feed updates in real-time. 

Conclusion  

React.js is a very new but also established library to make reusable view components that are encapsulated, sharable and easy to maintain. Many companies are using it in their production environments. The community is very active and extends React.js with new functionality on a daily basis. 

Learning React can make a world of difference to your career. React.js experts are highly sought after by established companies, to build user interfaces and help in the transition from old-fashioned technologies to one of the hottest new view libraries currently available. 

Profile

Rajesh Bhagia

Blog Author

Rajesh Bhagia is experienced campaigner in Lamp technologies and has 10 years of experience in Project Management. He has worked in Multinational companies and has handled small to very complex projects single-handedly. He started his career as Junior Programmer and has evolved in different positions including Project Manager of Projects in E-commerce Portals. Currently, he is handling one of the largest project in E-commerce Domain in MNC company which deals in nearly 9.5 million SKU's.

In his role as Project Manager at MNC company, Rajesh fosters an environment of teamwork and ensures that strategy is clearly defined while overseeing performance and maintaining morale. His strong communication and client service skills enhance his process-driven management philosophy.

Rajesh is a certified Zend Professional and has developed a flair for implementing PMP Knowledge Areas in daily work schedules. He has well understood the importance of these process and considers that using the knowledge Areas efficiently and correctly can turn projects to success. He also writes articles/blogs on Technology and Management