0

I'm trying to rewrite Chess Game from FB React tutorial using Typescript.

It's a long journey and quite challenging. I got this:

ERROR in ./src/Game.tsx
(79,15): error TS2322: Type '{ className: "square"; onClick: "{this.handleClick}"; }' is not assignable to type 'HTMLProps<HTMLButtonElement>'.
  Types of property 'onClick' are incompatible.
    Type '"{this.handleClick}"' is not assignable to type 'EventHandler<MouseEvent<HTMLButtonElement>>'.

This is my source code:

interface SquareProps extends React.Props<{}> {
}
interface SquareState {
    value: string
}
class Square extends React.Component<SquareProps, SquareState> {
  constructor(props: SquareProps) {
    super(props)
    this.state = { value: null }

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(): void {
    this.setState({value: 'X'})
  }

  render() {
    return (
      <button className="square" onClick="{this.handleClick}">
        {this.state.value}
      </button>
    );
  }
}

This is my package.json

{
  "name": "typescript-react-webpack",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --module-bind 'css=style!css'",
    "webpack-watch": "webpack --progress --colors --watch --module-bind 'css=style!css'",
    "start": "serve"
  },
  "devDependencies": {
    "serve": "^5.1.4",
    "ts-loader": "^2.0.0",
    "typescript": "^2.1.6",
    "webpack": "^2.2.1"
  },
  "dependencies": {
    "@types/react": "^15.0.23",
    "@types/react-dom": "^15.5.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  }
}

What am I doing wrong here?

1 Answer 1

7

It should be:

render() {
    return (
        <button className="square" onClick={ this.handleClick }>
            {this.state.value}
        </button>
    );
}

The difference being that the onClick value shouldn't be surrounded by quotes.
The quotes makes it a string instead of a reference to the method.

Sign up to request clarification or add additional context in comments.

2 Comments

OMG. You've just saved my day. It was a stupid newbie question. Thanks!
Sure thing. I also missed that you bound the method in ctor, I edited and removed that part of my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.