Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.map not being displayed in React Component

Tags:

reactjs

I'm trying to get this list in the view, but this doesn't display any items

render: function() {
    var list = this.state.list;
    console.log('Re-rendered');
    return(
        <ul>
        {list.map(function(object, i){
            <li key='{i}'>{object}</li>
        })}
        </ul>
    )
}

list is first set to null, but then I reload it with AJAX. This on the other hand works

    <ul>
    {list.map(setting => (
        <li>{setting}</li>
    ))}
    </ul>

This is my whole component as it stands:

var Setting = React.createClass({
   getInitialState: function(){
     return {
       'list': []
     }
   },
   getData: function(){
     var that = this;
     var myHeaders = new Headers();
     var myInit = { method: 'GET',
           headers: myHeaders,
           mode: 'cors',
           cache: 'default' };
    fetch('/list/',myInit)
        .then(function(response){
            var contentType = response.headers.get("content-type");
            if(contentType && contentType.indexOf("application/json") !== -1) {
            return response.json().then(function(json) {
                that.setState({'list':json.settings});
            });
            } else {
            console.log("Oops, we haven't got JSON!");
            }

        })
        .catch(function(error) {
            console.log('There has been a problem with your fetch operation: ' + error.message);
        });;    
   },
   componentWillMount: function(){
    this.getData();
   },
   render: function() {
    var list = this.state.list;
    return(
        <ul>
        {list.map(function(object, i){
            <li key={i}>{object}</li>
        })}
        </ul>
    )
  }
});
like image 543
cjds Avatar asked Feb 17 '17 21:02

cjds


1 Answers

You are missing your return statement

 {list.map(function(object, i){
   return <li key={i}>{object}</li>
 })}

this works

  <ul>
    {list.map(setting => (
        <li>{setting}</li>
    ))}
   </ul>

because anything within () is returned automatically when using an arrow function but the previous example was using {} which requires a return statement.

When should I use `return` in es6 Arrow Functions? this will give you more context around when and when not to use a return statement with arrow functions.

like image 160
finalfreq Avatar answered Nov 16 '22 02:11

finalfreq