ReactJS is a widely used JavaScript library for crafting user interfaces. It empowers developers to construct reusable components that can be combined effortlessly to create intricate user interfaces.
In this blog post, we’ll embark on a journey to construct a straightforward counter application in ReactJS, which will enable us to increment and decrement a counter value.
Starting Out
Our journey begins with the creation of a new React component named Counter. To manage the state, we will employ the state hook, which will give rise to a state variable named “count” and a function known as “setCount,” responsible for updating the state.
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
}
The useState hook necessitates an initial state value, which, in our case, is set to 0. At the outset of our file, we’re also importing the “useState” hook and the React library.
Adding Increment and Decrement Functions
Subsequently, we will define two functions: “incrementCount” and “decrementCount.” These functions will facilitate updates to the “count” state. The “incrementCount” function will increment the current count value by 1, while the “decrementCount” function will decrement it by 1.
function Counter() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
const decrementCount = () => {
setCount(count - 1);
};
}
Rendering the UI
Lastly, we will render the count value along with two buttons that invoke the “incrementCount” and “decrementCount” functions when clicked.
function Counter() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
const decrementCount = () => {
setCount(count - 1);
};
return (
<div>
<h1>{count}</h1>
<button onClick={incrementCount}>Increment</button>
<button onClick={decrementCount}>Decrement</button>
</div>
);
}
Within the return statement, we employ JSX syntax to present the count value and the two buttons. Additionally, we employ the “onClick” attribute to specify that the “incrementCount” and “decrementCount” functions should be invoked when the buttons are clicked.
Integrating the Component
To employ this component in another file, we merely need to import it and render it as shown below:
import React from "react";
import Counter from "./Counter";
function App() {
return (
<div>
<Counter />
</div>
);
}
export default App;
This code will render the Counter component and exhibit the increment and decrement buttons. When these buttons are clicked, the count value will be updated accordingly.
Final Remarks
Creating a basic counter application in ReactJS serves as an excellent starting point for familiarizing yourself with this library. It provides a hands-on opportunity to explore the useState hook and understand how to construct reusable components that can be seamlessly combined to construct intricate user interfaces.