Search code examples
reactjsformserror-handlingundefinedthis

this undefined in arrow function


I am creating a component that contains of a Form with a Submit button. In the OnSubmit of the Form I call an arrow function. Inside this function I call the object "this" but I get the error message that it is undefined. However, if I just do a console.log(this) in the OnSubmit of the form instead of calling the arrow function, this is defined. Anyone knows how to solve this issue ? I am actually following a react/ethereum course and even though the code of the instructor works in his video, his code doesn't work when I use it.

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

class CampaignNew extends Component{
  state = {
    minimumContribution: "",
    errorMessage: ""
  }

  onSubmit = async (event) => {
    event.preventDefault();
    this.setState({errorMessage: "test error"});
  }

  render(){
    return  (
                <div>
                  <Form onSubmit={this.onSubmit} error={this.state.errorMessage}>
                    <Form.Field>
                      <label>Minimum contribution</label>
                      <Input                        
                        labelPosition="right"
                        value={this.state.minimumContribution}
                        onChange={event => this.setState({minimumContribution: event.target.value})}
                        style={{width: "250px"}} placeholder='0' />
                    </Form.Field>
                    <Button type='submit' primary>Create</Button>
                  </Form>
                </div>
            )
  }
}

export default CampaignNew;

Solution

  • I found the problem. It was my version of NextJS. If I downgrade it to an earlier version, everything works fine. No idea why it breaks in the new version.

    Working version: "next": "^11.1.3"