How to Create a Simple Counter App in React JS
React JS is a popular JavaScript library for building user interfaces. In this article, we will learn how to create a simple counter app using React JS. This app will have a button to increase the counter value and another button to decrease the counter value. Let’s get started!
Step 1: Set Up Your Environment
First, make sure you have Node.js and npm installed on your machine. You can download and install them from the Node.js website if you don’t already have them.
Step 2: Create a New React App
Open your terminal and use the following command to create a new React app:
npx create-react-app counter-app
Step 3: Create the Counter Component
Inside the src folder of your new React app, create a new file called Counter.js. In this file, write the following code to create the Counter component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
Counter App
{count}
);
}
export default Counter;
Step 4: Use the Counter Component in App.js
Open the App.js file in the src folder and use the Counter component like this:
import React from 'react';
import './App.css';
import Counter from './Counter';
function App() {
return (
);
}
export default App;
Step 5: Run Your React App
In your terminal, navigate to the counter-app folder and run the following command to start your React app:
npm start
After your app is running, open your browser and go to http://localhost:3000. You should see your simple counter app in action!
Conclusion
Congratulations! You have just created a simple counter app in React JS. You can now build upon this app and add more features to it. React JS provides a great way to create interactive and dynamic user interfaces, and creating this simple counter app is just the beginning of what you can do with it!