Create counter app as your first react application.

Lizen Shakya
2 min readJul 16, 2022

--

React, a JavaScript library for creating interactive user interfaces(UI) is getting more popular by developers all around the world.

Before Starting

  1. Check if node is installed or not. You can use the below command line to check if you have node installed.
node -v

This should print the version number, so you will see something like v16.10.4

If you do not have node installed, then get that installed first.

2. Have a basic knowledge on:

Basic terms and concepts in React

Before forwarding, we need to understand some terms and concepts in React:-

1. Components — We do not have pages in a React app. It does only contain components. The react components are small reusable pieces of code that return a react element.

2. States — We already discussed that a React app only contains components instead of pages. So, some components may need to store some values. States are used to store these values which are specific for a component.

3. Props — If we want to pass a state from one component to another, props are used.

4. useState — A Hook that lets you add React state to function components.

Lets Start

Add the below command Line on your Terminal to create a new app within a new directory called counter-app

npx create-react-app react-counter-app
cd counter-app

npx stands for Node Package Execute. It is a package runner that comes with the npm that enables users to execute any package directly without installation.

After installing, go to src/App.js

Then replace the code with,

import { useState } from 'react';
import Button from './components/Button';
import './App.css';
function App() {
const [count, setCount] = useState(0);
const increaseCount = () => {
setCount(count + 1);
}
const decreaseCount = () => {
setCount(count - 1);
}
return (
<div className="App">
<div>
<h3>Count:</h3>
<h1>{count}</h1>
</div>
<div>
<button onClick={increaseCount}>Increase</button>
<button onClick={decreaseCount}>Decrease</button>
</div>
</div>
);
}
export default App;

We have created a state called count that will store the counter value. The state will be initially set to 0. Every time user will click either on Increase or Decrease, the value will change. The value will be displayed in the div with h1 tag.

So if we run using

npm run start

we can see the application running successfully.

Thank you!!

--

--

No responses yet