1

I playing reactjs v15 on copen. I got unexpected token = error on line

  _handleClick = (e) => {
    console.log(ReactDOM.findDOMNode(this.refs.input));
  }

Here is my fully react code on codepen: https://codepen.io/dotku/pen/QqwgVV?editors=1010

class Welcome extends React.Component {
  _handleClick = (e) => {
    console.log(ReactDOM.findDOMNode(this.refs.input));
  }
  render() {
    return <div>
      <h1>Hello, {this.props.name}</h1>
      <button onKeyPress={this._handleClick}>click</button>
      <input ref="input"/>
    </div>;
  }
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

Anyone has any idea why?

Weijing Lin
  • 575
  • 2
  • 5
  • 16
  • Possible duplicate of [How to use arrow functions (public class fields) as class methods?](https://stackoverflow.com/questions/31362292/how-to-use-arrow-functions-public-class-fields-as-class-methods) – Mayank Shukla Sep 14 '17 at 03:17

1 Answers1

0

Change your code like this. Just use a conventional function instead of an arrow function and bind it either in constructor, or inside the render function.

// class Input extends React.Component {
//   render() {
//     return <input type="text" value="aInput"/>;
//   }
// }
class Welcome extends React.Component {
  _handleClick(e) {
    console.log(ReactDOM.findDOMNode(this.refs.input));
  }
  render() {
    return <div>
      <h1>Hello, {this.props.name}</h1>
      <button onKeyPress={this._handleClick.bind(this)}>click</button>
      <input ref="input"/>
    </div>;
  }
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

An alternative is given in the comment above which needs you to enable experimental features in Babel as mentioned, if you need to go ahead with arrow functions. The following npm command would do the trick.

npm install --save-dev babel-plugin-transform-class-properties

Alternatively enabling the stage 2 features in Babel, would also do the trick if you really need to stick in to arrow functions.

npm install --save-dev babel-preset-stage-2
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63