codeAline
codeAline

Reputation: 429

Unexpected token, expected , in React component

I have a React component that looks like this

'use strict';

import 'babel-polyfill';
import React from 'react';
import TreeNode from './TreeView';

export default React.createClass({

  mapFromApi : function(data)  {
    const rec = (tree) => tree.reduce((x,y) => {

      const newObj = {
        "id" : y["@id"],
        "name" : y["rdfs:label"]
      };

      if (y.hasOwnProperty("options")) {
        newObj.children = rec(y.options, []);
      }
      if (y.hasOwnProperty("children")) {
        newObj.children = rec(y.children, []);
      }

      x.push(newObj);
      return x;
    }, []);

    let t = rec(data);

    return t;

  },
  render: function (data) {
    let tree1 = this.mapFromApi(this.props.data.properties).map(child => {
        return <TreeNode key={child['id']} data={child}/>;
    }.bind(this));

    return (
      <div className='vocab'>
      <h4>vocab1</h4>
        <div className='accordion'>
            {tree1}
        </div>
      </div>
    );
  }
});

When I run this I get an error on the bind keyword

SyntaxError: App.jsx: Unexpected token, expected , (56:5)
  54 |     let tree1 = this.mapFromApi(this.props.data.properties).map(child => {
  55 |         return <TreeNode key={child['id']} data={child}/>;
> 56 |     }.bind(this));
     |      ^
  57 |
  58 |     return (
  59 |       <div className='vocab'>

I'm not sure if this has to do with my Babel setup and I'm very confused about the whole es version situation.

Can some one help me resolve this? Many thanks.

Upvotes: 4

Views: 10487

Answers (2)

Dan Prince
Dan Prince

Reputation: 30009

If you simplify the way this code is laid out, these kind of syntax errors should be easier to identify.

let { data } = this.props;

this
  .mapFromApi(data.properties)
  .map(child => <TreeNode key={child.id} data={child} />)

The arrow function is already going to .bind(this) for you, so you can just omit that.

Upvotes: 2

HussienK
HussienK

Reputation: 3042

You shouldn't need to use .bind(this) because you are using the ES6 arrow function => and that will reference the correct this

I would write some thing like this

const {data} = this.props;

let tree1 = this.mapFromApi(data.properties).map(child => {
    return <TreeNode key={child['id']} data={child}/>;
});

Upvotes: 1

Related Questions