ReactJS - Rendering list or array of elements

Example to render list of items using components. How to generate ul li from array or list in ReactJS or JavaScript Here, many time we will get lists of item from database or api or other sources and we would have to display these values in either list view or in tabular form. In javascript we have many approached but this approach looks better to wrap each item from array or list in html tag without writing much of code.

Here, we have ItemLayout component which wrap values in li tag and we have another component which wrap the output of this ItemLayout component in ul tag. Hence we achieve ul, li based rendering of values stored in array or list.

Here, We have todoItems array in Item component, we want to display these values in ul li tags. For this we are using map function of javascript which iterates to each element of an array and return array back with the modification you did with call back function. Here, we are wrapping each element in map function inside ItemLayout component.

 

import React, { Component } from 'react'

class ItemLayout extends Component{

    render(){
        return <li key={this.props.id}>{this.props.id} = {this.props.name}</li>
    }
}

export default class Item extends Component {
     todoItems=[
         {"id":"1","name":"task one"},
         {"id":"2","name":"task two"},
         {"id":"3","name":"task three"},
         {"id":"4","name":"task four"},
         {"id":"5","name":"task five"},

    ];

    items=this.todoItems.map((itm)=><ItemLayout key={itm.id} id={itm.id} name={itm.name} />);

    render() {
        return (
            <div>
                <h1>Todo Items</h1>
                <h2>List of Items</h2>
                <ul>{this.items}</ul>
            </div>
        )
    }
}

 

Tags