In this post, we’ll build a simple Medium clapper with React. But before we get to the clapper, let’s go over some basic concepts of React: props
, state
, and setState
.
What is React?
React is a JavaScript library with which you can build user interfaces. Each React Component must implement a render()
method that returns what to display. A React Component can also take input data, which the render()
method can access via this.props
.
In this example, we pass the beverage as props to the App component (on line 17), and the App component displays “Hello, would you like a {beverage}?” in its render()
method. Fork the sandbox above and try changing the beverage!
Maintaining state
When we need a component to maintain and change an internal state, we can use this.state
.
For instance, we can let our user refuse and choose another beverage. To add chosenBeverage
to state, we add a constructor to our component, and set our initial value of chosenBeverage
to a blank line. We display this in our render()
method like, “No, I’d prefer some {chosenBeverage}.”
To let our user pick a beverage, let’s add a few buttons for different kinds of beverages. When the user clicks a button, we need to change our state to reflect the change in chosenBeverage
. We can do this using a chooseBeverage()
function, which takes the chosen beverage as a parameter. Since we need to change state, we call the setState()
function, that takes an object which React will merge into state.
We add onClick
parameters to our buttons to call the chooseBeverage()
function when clicked.
Try it out for yourself here:
Making a medium clapper
Now that we know how to use props
, state
and setState
, let’s make our medium clapper!
To keep track of the number of claps, we set our initial value of claps
to 0 and display the number of claps in the render()
method:
We add a function called incrementClaps()
. This function calls setState()
to increment the number of claps. Since we’re calculating the state based on our previous state, we use another version of setState()
, one that takes an updater function as a parameter. The updater function takes the previous state and current props as input and returns an object that needs to be merged with state.
We add a clap button which has an onClick
parameter to call the incrementClaps()
function when clicked.
And there you have it! A simple medium clapper with React!