anthony-dandrea
anthony-dandrea

Reputation: 2813

this.setState is not a function for textfield

Trying to do validations on a textfield while the user is typing in a text field. I want to change the state of the errorText attribute on the fly.

I receive the error Uncaught TypeError: this.setState is not a function when trying to set the state. Relevant code below.

export default class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            username: null,
            errorCopy: null
        };
    }
    handleChange(e) {
        this.setState({errorCopy: 'Generic error copy'});
    }
    render() {
        return(
            <TextField
                hintText="Username"
                value={this.state.username}
                onChange={this.handleChange}
                errorText={this.state.errorCopy} />
        )
    }
}

Upvotes: 1

Views: 2638

Answers (1)

anthony-dandrea
anthony-dandrea

Reputation: 2813

Whoops, in ES6 class binding has to be done manually.

Needed to add .bind(this) to the handleChange

export default class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            username: null,
            errorCopy: null
        };
    }
    handleChange(e) {
        this.setState({errorCopy: 'Generic error copy'});
    }
    render() {
        return(
            <TextField
                hintText="Username"
                value={this.state.username}
                onChange={this.handleChange.bind(this)}
                errorText={this.state.errorCopy} />
        )
    }
}

Upvotes: 3

Related Questions