ReactJS is a popular JavaScript library used for building user interfaces. It allows developers to create reusable components that can be easily composed to build complex UIs. In this blog post, we'll be exploring how to build a simple counter app in ReactJS that increments and decrements a counter value.
To get started, we'll create a new React component called Counter. We'll use the state hook to create a state variable called count and a function called setCount that will be used to update the state.
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
// ...
}
The useState hook takes an initial state value, which in our case is 0. We're also importing the useState hook and the React library at the top of our file. Next, we'll define two functions called incrementCount and decrementCount that will be used to update the count state. The incrementCount function simply adds 1 to the current count value, while the decrementCount function subtracts 1.
function Counter() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
const decrementCount = () => {
setCount(count - 1);
};
// ...
}
Finally, we'll render the count value and two buttons that call 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>
);
}
In the return statement, we're using JSX syntax to render the count value and two buttons. We're also using the onClick attribute to specify that the incrementCount and decrementCount functions should be called when the buttons are clicked.
To use this component in another file, we simply need to import it and render it like this:
import React from "react";
import Counter from "./Counter";
function App() {
return (
<div>
<Counter />
</div>
);
}
export default App;
This will render the Counter component and display the increment and decrement buttons. When the buttons are clicked, the count value will be updated accordingly.
Final Thoughts
Creating a simple counter app in ReactJS is a great way to get started with the library. It allows you to explore the useState hook and learn how to create reusable components that can be easily composed to build complex UIs
We welcome your feedback and thoughts – please share your comments!