Whymess
Whymess

Reputation: 717

React initial state. counting

What am I doing wrong, I keep getting TypeError: Cannot read property 'count' of null. Am I not setting the initial state up properly?

import React from 'react';

class User extends React.Component {
	super(props){

		this.state = {
			count: 0
		}
	}


	increment(){
		this.setState({ count: this.state.count + 1 })
	}

	render(){
		return(<div>
			<button 
				onClick={this.increment}>
						{this.state.count}
			</button> 


		 </div>)
	}
}




export default User;

Upvotes: 1

Views: 579

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77512

Set this to .increment method, because when you pass method .increment to onClick it loses context which related to User component. Instead of super(props) you have to use constructor(props);

class User extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }

    this.increment = this.increment.bind(this);
  }


  increment(){
    this.setState({ count: this.state.count + 1 })
  }

  render() {
    return (
      <div>
        <button 
          onClick={this.increment}
        >
          { this.state.count }
        </button> 
      </div>
    )
  }
}

ReactDOM.render(<User />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Also you can use arrow function, like so

onClick={() => this.increment() }

Upvotes: 1

Related Questions