mannuk mannuk - 2 months ago 6
React JSX Question

Can't iterate React component to create table. Unexpected token

I'm trying to create a table filled by a REST API using ReactJS. The problem is I don't know what I'm doing wrong with the sintax... I'm using ES6.

This is the FooTable:

import React from 'react'
import Foo from './Foo'

export default class FooTable extends React.Component {

render() {
return(
<tr>
<td>id</td>
<td>name</td>
<td>surname</td>
</tr>
{ //<-- This is the marked error by webpack
this.props. Foos.map( foo=>{
return < Foo key={foo.id} name={foo.name} surname={foo.surname}/>
})
}
)
}//end-render
}


This is the Foo class:

import React from 'react'

export default class Foo extends React.Component {
render() {
return <tr>
<td>{foo.name}</td>
<td>{foo.surname}</td>
</tr>
}
}


This is the main render:

render(){
if (this.state.foos.length > 0) {
console.log('Foos size ' + this.state.foos.length);
return <table>
<tbody>
<FooTable foos={this.state.foos}/>
</tbody>
</table>
} else {
return <p className="text-center">Loading Foos...</p>
}
}


Webpack marks an error in FooTable (Unexpected Token). It's marked by a comment.

Answer

you need to return single node from your component's (FooTable in this case )render method.

render() {
    return(
    <tr>
      <td>id</td>
      <td>name</td>
      <td>surname</td>
    </tr>
    { //<-- This breaks the single root
      this.props.Foos.map( foo=>{
             return  < Foo key={foo.id} name={foo.name} surname={foo.surname}/>
      })
    }
    )
  }

you need to do sth like this :

render() {
    return (
      <tbody>
        <tr>
          <td>id</td>
          <td>name</td>
          <td>surname</td>
        </tr>
        {this.props.Foos.map(foo => (<Foo key={foo.id} name={foo.name} surname={foo.surname}/>))}
    </tbody>)
  }