Building a Simple Counter App with ReactJS
In this exercise, you will build a simple counter app using ReactJS. The app will have a button that, when clicked, increments a counter. Here’s what you need to do:
- Set up a new ReactJS project
You can use the Create React App tool to quickly set up a new ReactJS project. Simply run the following command in your terminal:
lua
npx create-react-app my-counter-app
- Create a new component
In your newly created ReactJS project, create a new component called “Counter”. This component will be responsible for rendering the counter and the button. To do this, create a new file called “Counter.js” in the “src” directory.
- Write the component’s state
The state of the component will contain the counter value. To define the state, you can use the useState
hook. Add the following code to the “Counter.js” file:
javascript
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
This code defines a simple component that contains a paragraph element displaying the counter value and a button that, when clicked, increments the counter value by calling the setCount
function.
- Render the component
Next, you need to render the “Counter” component in your ReactJS app. To do this, open the “src/App.js” file and replace the contents with the following code:
javascript
import React from 'react';
import Counter from './Counter';
function App() {
return (
<div className="App">
<Counter />
</div>
);
}
export default App;
- Start the app
Now that you have written the code for your counter app, you can start the app by running the following command in your terminal:
sql
npm start
This will start the app in your browser and you should see the counter value displayed on the screen along with the “Increment” button.
- Test the app
Finally, test the app by clicking the “Increment” button. You should see the counter value increment each time you click the button.
Congratulations! You have successfully built a simple counter app using ReactJS.