简体   繁体   中英

Map() not returning JSX when called through a function

I am trying to output a bunch of li's while iterating through a map function. The issue is that the code works when directly placed inside the render return statement but stops working if I organize it in a helper function and call the function at the return statement.

WORKS:

const UserList = (props) => {
  if(props.items.length === 0){
    return (
      <div className="center">
        <h2>No users found.</h2>
      </div>
    );
  }
}

return <ul className="users-list">
  {
    props.items.map(user => {
      console.log(user.name);
      return <li>{user.id}</li>   
    })
  }
</ul>

DOESN'T WORK:

const UserList = (props) => {
  if(props.items.length === 0){
    return (
      <div className="center">
        <h2>No users found.</h2>
      </div>
    );
  }
}

const renderList = () => {
  props.items.map(user => {
    console.log(user.name);
    return <li>{user.id}</li>   
  })
};

return <ul className="users-list">
  {renderList()}
</ul>

You need to have return statement on your method.

const { items } = props; 

const renderList = () => {
  return items.map(user => {
      return <li>{user.id}</li>   
    }
  )
};

Or a short version with less code. In arrow functions you don't need to write down the curly braces and the return statement if you only return a result without further processing.

const { items } = props; 

const renderList = () => items.map(user => <li>{user.id}</li>);

do this:

const renderList = () => {
    return props.items.map(user => {
        console.log(user.name);
        return <li>{user.id}</li>   
      }
    )
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM