N Sharma
N Sharma

Reputation: 34497

How to render list items in reactjs

I am using List to render the data vertically. Docs suggests a way for hardcoded data but I have data in an array.

Docs have this example :

<MobileTearSheet>
  <List>
    <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
    <ListItem primaryText="Starred" leftIcon={<ActionGrade />} />
    <ListItem primaryText="Sent mail" leftIcon={<ContentSend />} />
    <ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} />
    <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
  </List>
  <Divider />
  <List>
    <ListItem primaryText="All mail" rightIcon={<ActionInfo />} />
    <ListItem primaryText="Trash" rightIcon={<ActionInfo />} />
    <ListItem primaryText="Spam" rightIcon={<ActionInfo />} />
    <ListItem primaryText="Follow up" rightIcon={<ActionInfo />} />
  </List>
</MobileTearSheet>

I have todos array which I want to render in a ListItem. Can anyone suggest me how to do ?

this.state = {
  open: false,
  todos: [],
  notetext: ""
};

I am adding elements in an array as below:

todos.push({
  id: todos.length,
  text: this.state.notetext,
  completed: false
});

Upvotes: 4

Views: 6824

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Use map to iterate the todos array, then for each item of the array create a ListItem element.

Write it like this:

_renderTodos(){
    return this.state.todos.map(el => {
        return <ListItem primaryText={el.text} key={el.id}/>
    })
}

render(){
    return(
        <MobileTearSheet>
            <List>
                {this._renderTodos()}
            </List>
        </MobileTearSheet>
    )
}

Check this snippet:

class App extends React.Component{
    
     constructor(){
        super();
        this.state = {
           a: [1,2,3,4]
        }
     }
  
     _renderItems(){
         return this.state.a.map(el => <p>{el}</p>)
     }
     
     render(){
        return(
            <div>
                {this._renderItems()}
            </div>            
        )
     }
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Upvotes: 4

Ji aSH
Ji aSH

Reputation: 3457

Iterate on your array with something like that:

_buildItem(item, index) {
    return <ListItem key={index} primaryText={item.text}/>
}

render() { return (
    <List>
        {this.state.todos.map(this._buildItem)}
    </List>
)}

Upvotes: 0

Related Questions