Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash map get index key got unexpected token

import { map } from 'lodash';

render(){
   return(
      {map(new_applicants, (obj,index) => 
         <div key={index}>{index}</div>
      )}
   )
}

What's wrong with this code? obj is the single array of object been iterate and index is the key. I'm using lodash. The error look like this in console.

{map(new_applicants, (obj,index) => 
     |               ^
like image 511
Giala Jefferson Avatar asked Apr 13 '17 04:04

Giala Jefferson


2 Answers

The problem is that the {...} syntax is being taken for an object initializer; you're doing this outside of JSX. That syntax is only valid within a JSX section, e.g.

<div>{map(...)}</div>

Also, render has to return a component (or null), it can't return an array. So perhaps:

return(
  <div>
  {map(new_applicants, (obj,index) =>
    <div key={index}>{index}</div>
  )}
  </div>
)

Example:

const map = _.map;

class Foo extends React.Component {
  render() {
    const new_applicants = [1, 2, 3];
    return(
      <div>
      {map(new_applicants, (obj,index) =>
        <div key={index}>{index}</div>
      )}
      </div>
    )
  }
}

ReactDOM.render(
  <Foo />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
like image 80
T.J. Crowder Avatar answered Nov 05 '22 09:11

T.J. Crowder


Write it like this, {} it required when you are running the js code inside html element:

render(){
   return( 
      <div>
        {
            map(new_applicants, (obj,index) => 
              <div key={index}>{index}</div>
            )
        }
      </div>
   )
}
like image 31
Mayank Shukla Avatar answered Nov 05 '22 10:11

Mayank Shukla