Cow Pow Pow
Cow Pow Pow

Reputation: 127

React component "unexpected token function"

My JSX was transpiling just fine until I tried to add my first function besides render(), namely send().

import React from 'react';
import ReactDOM from 'react-dom';

class Lobby extends React.Component {

    send: function() {
        alert("chat-send button clicked");
    },

    render() {
        return (
            <div> 
                <button onClick={this.send} id="chat-send">Send</button>
            </div>
        )
    };
}

ReactDOM.render(<Lobby />, document.getElementById("chat-pin"));

I'm receiving an error that says

SyntaxError: /pathname.../file.js: Unexpected token

and then the keyword function is pointed out from send: function().

I was rendering React, so what could be the problem? Here is my gulp file doing the heavy lifting for me:

//-----------------------------------------------------------------------------
// gulpfile.js
// Gulp is our task runner. Currently being used to transpile ES6 and React.
//-----------------------------------------------------------------------------
const gulp = require('gulp');
const babelify = require('babelify');
const browserify = require('browserify');
const source = require("vinyl-source-stream");
const buffer = require("vinyl-buffer");

//-----------------------------------------------------------------------------
// Transpile the ES6 and React code.
//-----------------------------------------------------------------------------
gulp.task('js', () => {
    return browserify({ entries: ['react-src/LobbyChatReact.js'] })
    .transform(babelify, {
        presets: ["react", "es2015"],
        plugins: ["transform-class-properties"] })
    .bundle()
    .pipe(source('LobbyChatReact.js'))
    .pipe(gulp.dest('public/javascripts/react-build'));
});

//-----------------------------------------------------------------------------
// Listen for changes in react-src folder. When changes detected, transpile.
//-----------------------------------------------------------------------------
gulp.task('default', ['js'], () => {
    gulp.watch('react-src/LobbyChatReact.js', ['js']);
});

It was my understanding that neither the "react" or the "es2015" presets covered class properties, and so I would have to get the "transform-class-properties" plugin.

Can anyone see what is going wrong here?

Upvotes: 1

Views: 6890

Answers (1)

Anuj
Anuj

Reputation: 1474

The function definition should be:

send() {

Instead of

send: function() {

We don't add the function keyword when defining methods in classes

Upvotes: 6

Related Questions