# How to React (quickly)

matt2xu
9,589 views

## Event handling

Until now the buttons in our counter had no effect. In the following example, we will add event handlers to the plus and minus buttons. First, we define an array of possible actions INCREMENT and DECREMENT, along with a labels prop that defines the labels of our buttons. Right now, all we will do is log the action received in the console.

Fix the first snippet on the right to handle clicks on the buttons to call the event handler.

Counter with event handling

## Components with class

So far we've only dealt with so-called functional components. Our counter is indeed a pure function that take inputs (initial count, labels) and returns a virtual DOM with a paragraph and buttons. What we would like, though, rather than just printing in the console when the user increments/decrements the counter, is to store and print the current value of the counter. For that, we will need to define a component that can have a state.

A stateful component is typically defined as a class extending React.Component and implementing a render function that returns the virtual DOM for that component. To have state, the constructor of that component defines a state variable with the properties that we will use.

Add a count property to the state of the component in the counter-class code.

Counter class

## State

To update the state of a component, the component must call the setState function with an argument that is the update function. The update function takes the current state and the props as arguments, and must return an object with the properties of the state that should be updated to a new value. Other properties remain the same.

In the last code snippet, implement the decrement action in the handleClick method:

Stateful counter
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
const ACTIONS = ['INCREMENT', 'DECREMENT'];
const Counter = ({initialCount, labels}) => {
let handleClick = action => {
console.log(Received action \${action})
}
return (
<div>
<p>Number of items: {initialCount}</p>
{ACTIONS.map(action =>
<button
key={action}
onClick={void 0 /* TODO: define a function that calls handleClick(action) */}
>
{labels[action]}
</button>)}
</div>
)
}
Counter.propTypes = {
initialCount: PropTypes.number.isRequired,
labels: PropTypes.objectOf(PropTypes.string).isRequired
}
Counter.defaultProps = {
initialCount: 0
}
ReactDOM.render(<Counter labels={{INCREMENT: '+', DECREMENT: '-'}} />, document.getElementById('root'))
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
Online Participants