Exercise: Building a simple counter app in ReactJS

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:

  1. 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:

npx create-react-app my-counter-app
  1. 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.

  1. 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:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>

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.

  1. 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:

import React from 'react';
import Counter from './Counter';

function App() {
  return (
    <div className="App">
      <Counter />

export default App;
  1. 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:

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.

  1. 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.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *