Abhilash D K
Abhilash D K

Reputation: 1309

this.state is null inside render React and Typescript

I am a novice in ReactJS. Was watching a tutorial that is recorded in ES6 JavaScript and simultaneously I am trying to recreate the same app in TypeScript (I am a novice in TypeScript too!!). In ES6 we need to use a class based approach if that particular component needs to maintain it's own state. I have installed "babel-plugin-transform-class-properties" so i do set state in ES6 as export default class SomeClass { state = { someProperty : someValue }}. But in TypeScript I am using class based approach for every component. So here is a component that tries to maintain it's own state:

import React from 'react';

interface IAddOptionProps {
    handleAddOption: (option: string) => string |null;
};

interface IAddOptionState {
    error: any;
};

export default class AddOption extends React.Component<IAddOptionProps, IAddOptionState> {
    handleAddOption = (e:any) => {
        e.preventDefault();
        const option = e.target.elements.option.value.trim();
        const err : string = this.props.handleAddOption(option);

        this.setState(() => {
            return {
                error: err
            }
        });

        if (!err) {
            e.target.elements.option.value = '';
        }
    }

    render() {
        console.log(this.state);
        return (
            <div>
                {this.state.error != null ? <p>{this.state.error}</p> : ''}
                <form onSubmit={this.handleAddOption}>
                    <div className="form-group">
                        <label>Enter an Option</label>
                        <input type="text" className="form-control" id="option"  name="option"/>
                    </div>
                    <button className="btn btn-primary">Add option</button>
                </form>
            </div>
        );
    }
};

The statement console.log(this.state); and {this.state.error != null ? <p>{this.state.error}</p> : ''} inside render() is throwing error stating that Uncaught TypeError: Cannot read property 'error' of null. That means this.state is being set as null.

Why is state getting set to null and how do I resolve this ( In TypeScript )?

Thanks in Advance.

Upvotes: 4

Views: 4946

Answers (2)

Edoardo L&#39;Astorina
Edoardo L&#39;Astorina

Reputation: 7285

You have to initialize your state. There are two ways to do that

The first is to use a property initializer

class AddOption extends React.Component<IAddOptionProps, IAddOptionState> {

  this.state = {
    error: ''
  };

  render() {

    // Now you have your state! Do stuff here

  }

}

The other way is to do it in the constructor

class AddOption extends React.Component<IAddOptionProps, IAddOptionState> {

  constructor(props) {
    super(props);

    this.state = {
      error: ''
    };
  }

  render() {

    // Now you have your state! Do stuff here

  }

}

The solutions are equivalent, though the first is more elegant

Upvotes: 2

chkal
chkal

Reputation: 5668

As already mentioned in the comments, you have to initialize the state either in the constructor or with a property initializer like this:

class AddOption extends React.Component<IAddOptionProps, IAddOptionState> {

  this.state = {
    error: ''
  };

  [...]

}

Otherwise state will be null and you will get an error like mentioned in your post.

Upvotes: 5

Related Questions