-
Notifications
You must be signed in to change notification settings - Fork 0
React: State and events
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.
- Switch to the
hello
branch andpull
the latest changes. - In the
Hello
component, using the React hook for creating state,useState()
, create a state variable calledcounter
. - Add a
button
component in yourHello
component somewhere. In theonClick
handler for this button, use the setter function of yourcounter
(hopefully namedsetCounter()
) to incrementcounter
by 1. Hint: You will need to wrap your code in another function. How would you do that? - In your
Hello
component, display the text "The counter was clicked {counter} times." Figure out how you can make the value of thecounter
variable show up in this text instead of the word "counter". Hint: the answer is easier/more confusing than I am letting on. - Check if your code works. If it works, send a message on the channel saying you are done! Good job!
- 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: