In this task, you will create a simple counter app using React. The app should have the following features:
Open the src/index.css
file and add the following global styles:
Save the file and check the changes in the browser.
Let’s update the src/App.tsx
file to create the layout for the counter app.
Notice what the App
function returns is fairly similar to the layout we created in the previous task.
Let’s break down the differences:
We are using JSX syntax in the React component (App
function) instead of string interpolation. This makes the code more readable and maintainable. Here we would not be making mistakes like forgetting to close a tag or missing a closing quotation mark which can happen when using string interpolation.
We are using className
instead of class
for adding CSS classes to the elements. This is because class
is a reserved keyword in JavaScript, so React uses className
to avoid conflicts.
We are wrapping the JSX code in a div
element. This is because each React component (the App
function in this case) should return a single root element. If you have multiple elements to return, you need to wrap them in a parent element. In this case, we are using a div
element as the parent. It is common to use a fragment (<></>
) instead of a div
if you don’t want to introduce an extra div
in the DOM.
React apps are made up of components, which are reusable pieces of code that represent parts of the user interface. In this case, the App
component represents the entire counter app.
Each component is a function that returns a React Element, which is a JavaScript object describing a DOM node (HTML element) and its properties. We use JSX (JavaScript XML) syntax to create these React Elements.
JSX allows us to write HTML-like code within our JavaScript or TypeScript files, making it easier to express the structure and content of our UI components. It is then transpiled into regular JavaScript code by tools like Babel or TypeScript.
By using JSX, we can leverage the full power of JavaScript to dynamically generate and manipulate the UI, while also benefiting from the readability and familiarity of HTML-like syntax.
Update the src/App.css
file with the following styles:
We keep the styles related to the counter in a separate CSS file (App.css
) from the global styles (index.css
). This helps in organizing the styles and keeping them modular.
Save the file and check the changes in the browser.
In the App
component, let’s use a variable to store the counter value.
Notice that we are using the const
keyword to declare a variable count
and initializing it with the value 0
. This variable will hold the current value of the counter.
To display the value of the counter, we are using {count}
inside the div
element with the id counter
. This is an example of interpolation in JSX, where we can embed JavaScript expressions within curly braces {}
to include dynamic content in our components.
Try the following code changes and view the updated counter value in the browser.
count
to 10
and see how the counter value changes.{count}
expression to {count + 5}
and see how the counter value is updated.Reset the value of count
to 0
and update the {count + 5}
expression back to {count}
before moving to the next step.
We need to add event handlers for the buttons to increment, decrement, and reset the counter value.
In the App
component, we have defined a function updateCounter
that takes an action as an argument (increment
, decrement
, or reset
) and updates the count
variable accordingly. We changed the count
variable to let
so that we can reassign its value inside the function.
We are using the onClick
event handler to call this function when the buttons are clicked. The arrow function syntax () => {}
allows us to pass arguments to the updateCounter
function based on the button clicked. Notice how we can do this directly in JSX whereas in vanilla JavaScript we would have to get the element by id and then attach an event listener. The only difference is that in React, we use camelCase for event names like onClick
instead of onclick
.
Try clicking the buttons in the browser and observe how the counter value changes. You should see the counter value logged to the console each time a button is clicked.
To update the counter value in the UI when the buttons are clicked, we need to use state in React. State allows us to manage and update data within a component, and when the state changes, React automatically re-renders the component to reflect those changes.
Let’s update the App
component to use state for the counter value.
In this updated version of the App
component, we are using the useState
hook from React to create a state variable count
and a function setCount
to update the value of count
. The useState
hook takes an initial value (0
in this case) and returns an array with the current state value and a function to update that value.
When the buttons are clicked, we call the updateCounter
function with the appropriate action (increment
, decrement
, or reset
). Inside this function, we use setCount
to update the value of count
based on the action.
React will automatically re-render the component when the state changes, so the counter value displayed in the UI will be updated accordingly.
Try clicking the buttons in the browser and observe how the counter value changes. You should see the counter value updated in the UI (without any console logs since we removed the console.log(count)
statement).
useState
HookThe useState
hook is a built-in function in React that allows React components to manage state. State refers to data that can change over time and affects the behavior and appearance of the component.
When you call useState
, it returns an array with two elements: the current state value and a function to update the state. The initial state is provided as an argument to useState
.
For example, in the code snippet const [count, setCount] = useState(0);
we are initializing the state variable count
with the value 0
and the function setCount
to update the value of count
.
When you call setCount(newValue)
, React will update the state value and re-render the component to reflect the changes. This is how React manages the state of a component and ensures that the UI is always in sync with the data.
You should never modify the state directly in React. Always use the setter function provided by useState
to update the state. This ensures that React can track the changes and trigger re-renders when necessary.
In this task, you created a simple counter app using React. You learned how to:
useState
hook to manage state in functional components.onClick
to respond to user actions.