Skip to content

React: State and events

Deepanshu Utkarsh edited this page Oct 10, 2019 · 2 revisions

You created a Hello World example in React. But you could've done that using plain HTML. Why React? That's where something called 'state' comes in. I am going to italicize state when I mean the English word meaning the particular condition something is in. When I am talking about the React concept called state, I will simply say state.

State is one of the few mechanisms for representing your app's or component's state in React. I know it is confusing wording, but you will get used to the quirks, you go to Tufts. It's usually used for holding small pieces of information specific to a particular component. You will see an example soon.

We are going to modify the Hello World example and add a button to it. When someone clicks this button, a counter stored as a state increments by 1. We are going to display this number with our text as "Hello, world! The counter was clicked {counter} times."

Here are some intentionally vague steps on how to modify the code in the hello branch to be able to do this. Your job is to figure out exactly how. You will need to Google some things, ask in our Slack channel when you get stuck and ask me if you are still stuck.

  1. Switch to the hello branch and pull the latest changes.
  2. In the Hello component, using the React hook for creating state, useState(), create a state variable called counter.
  3. Add a button component in your Hello component somewhere. In the onClick handler for this button, use the setter function of your counter (hopefully named setCounter()) to increment counter by 1. Hint: You will need to wrap your code in another function. How would you do that?
  4. In your Hello component, display the text "The counter was clicked {counter} times." Figure out how you can make the value of the counter variable show up in this text instead of the word "counter". Hint: the answer is easier/more confusing than I am letting on.
  5. Check if your code works. If it works, send a message on the channel saying you are done! Good job!
  6. If you want, you can create a branch for your code and push it to the repository. Create a pull request if you want me to review your code, or if you just want practice with pull requests.

Hopefully you are done with this example by this weekend so you have time to enjoy it. :) Don't hesitate to message our Slack channel for questions. I expect you to either be done with the example or have asked questions if you are stuck by our meeting on Monday. Good luck!

References:

React Hooks