Let's write a simple counter, and below we will analyze it in more detail

class Counter extends Component { constructor(props, context) { super(props, context) this.state = { counter: 0 } } handleClick(event) { event.preventDefault() this.setState({ counter: this.state.counter + 1 }) } render() { const { div, a, p } = html return ( div({}, p({}, this.state.counter), a({ href: '#click', onClick: event => this.handleClick(event) }, 'Click me!' ) ) ) } }

Default state

To set the default counter state, we need to implement the constructor and pass the props and context arguments to the base class via the super method. Now you can set the initial state in this.state.

New state

In the handleClick method, we set a new state through the this.setState method.

When you install it the following happens:

Do not modify this.state object directly, always use this.setState method otherwise nothing will happen.

Click handler

In the render method for the link, set the onClick property handleClick. Wrap the handler into arrow function so this refers to this object.

Our counter is ready.