Unexpected token expected in React component

I have a React component that looks like

'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 for 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 is related to my Babel setup, and I am very confused about the whole es version situation.

Can someone help me solve this? Many thanks.

+4
source share
2 answers

If you simplify the way you write this code, these types 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 sent .bind(this)for you, so you can just omit this.

+2
source

.bind(), ES6 arrow => this

-

const {data} = this.props;

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

Source: https://habr.com/ru/post/1665347/


All Articles