React Components and State Control

React Logo

This week I have been learning React and to help with my learning I have created a small web app (Not yet published on this server, but I will provide the Github link in this post of the source code).  This app is simple in concept it basically takes an input from a user, the user can type as many inputs as they wish essentially to build up a list of things to do, they can then click a button and the computer will show at random an item from their list saying that this is what they should do.  It’s rather crude but I’ve learnt a lot of concepts such as React components and State handling.

However for the purpose of this post I will be describing how you can build a simple Counter app that has 3 buttons +1, -1 and reset and this will update a counter on the screen the counter will start from 0 (zero)

React Components

You have a website and that site has a header, footer, main body and a side bar, you can think of these as components and essentially that’s what a React Component is, React Components can contain sub components like a website side bar may contain a search section or a profile section.

To hold all these components, I created a Dashboard component (effectively a container) this is essential a class:

Then to render this to the screen.

Now to be able to use “this” keyword as shown in the code above we need to override the React.Component constructor and then bind our methods.

So the above now becomes this:

React State

You will notice the below, this is used within the constructor to see the initial state of the JavaScript object count to 0.

Now we can add our methods

The setState method allows us to control the state of our object, it also allows for an optional parameter which I have called prevState to handle what the previous state was.

The Final Code for Counter:

As I learn more about React I will continue posting articles and improving the quality of such posts.

Full source Code can be downloaded from here:



Leave a Reply

Your email address will not be published. Required fields are marked *