mfisher91
mfisher91

Reputation: 807

React - "Unexpected token" when initialising state

I'm fairly new to React, so please forgive any errors in this question!

I'm currently trying to get a basic login form working:

import React, { Component } from 'react';
import { Input, Form, Button } from 'semantic-ui-react'

class LoginForm extends Component {

  state = { username: '', password: '' }

  handleChange = (e, { name, value }) => this.setState({ [name]: value })

  handleSignIn(e) {
    e.preventDefault()
    this.props.onSignIn(this.username, this.password)
  }

  render() {
    const { username, password } = this.state

    return (
      <div className="login-container">
        <Form onSubmit={this.handleSignIn.bind(this)}>
          <Form.Field>
            <Input icon="user" iconPosition="left" placeholder="Username" type="text" ref="username" onChange={this.handleChange}/>
          </Form.Field>
          <Form.Field>
            <Input icon="user secret" iconPosition="left" placeholder="Password" type="password" ref="password" onChange={this.handleChange}/>
          </Form.Field>
          <Form.Field>
            <Button type="submit" className="inputSpacing" color="yellow"><Icon name='lock' />Login</Button>
          </Form.Field>
        </Form>
      </div>
    );
  }
}

export default LoginForm;

The issue that I'm facing is that the state = { username: '', password: '' } line generates the following error:

ERROR in ./react-client/src/components/coreComponents/loginForm.js Module build failed: SyntaxError: D:/path/to/project/react-client/src/components/coreComponents/loginForm.js: Unexpected token (6:8)

I've copied this from here, but even the code snippets there give me this error. What am I missing? :(

Upvotes: 1

Views: 4315

Answers (3)

Philippe
Philippe

Reputation: 1030

As mentioned on a similar issue on github. You should edit your .babelrc file to be able to use this syntax.

{
  "presets": [
    ["es2016"],
    "react"
  ],
  "plugins": [
    "babel-plugin-transform-class-properties"
  ]
}

Upvotes: 3

devserkan
devserkan

Reputation: 17608

You don't have name properties for your Input's.

<Input name="username" icon="user" iconPosition="left" placeholder="Username" type="text" ref="username" onChange={this.handleChange}/>
<Input name="password" icon="user secret" iconPosition="left" placeholder="Password" type="password" ref="password" onChange={this.handleChange}/>

Upvotes: 1

Ayan
Ayan

Reputation: 8886

Enclose it within a constructor. And also you need to bind your state to your component with this keyword

  constructor() {
    super();
    this.state = {
      username: '', password: ''
    };
  }

Upvotes: 1

Related Questions