Hands-On - Simple Counter
Goal : Build Lift State Up - Hands-On Simple Counter App
the step-by-step procedure to implement a simple Counter React App:
Setup Your React Environment: Make sure your development environment is set up with React. Use
create-react-appor another method to scaffold a new React application.Install Bootstrap: Use the following command to install Bootstrap:
npm install bootstrapImport Bootstrap Styles: Add the following import statement at the top of your
App.jsxfile orindex.jsfile:import 'bootstrap/dist/css/bootstrap.min.css';Create the Counter Component:
Create a functional component named
Counterthat receivescount,onIncrement, andonDecrementas props.Add Bootstrap styles to the buttons for better appearance.
Set Up the Parent Component:
In the
Appcomponent, use theuseStatehook to manage thecountstate.Define
handleIncrementandhandleDecrementfunctions to update the state when the buttons are clicked.Pass these functions and the
countstate as props to theCountercomponent.
App.jsx
// App.jsx
// Import required libraries
import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
// Counter Component
function Counter({ count, onIncrement, onDecrement }) {
return (
<div className="text-center mt-5">
<h1>Counter App</h1>
<h2 className="my-4">Count: {count}</h2>
<button
className="btn btn-primary mx-2"
onClick={onIncrement}
>
Increment
</button>
<button
className="btn btn-danger mx-2"
onClick={onDecrement}
>
Decrement
</button>
</div>
);
}
// App Component (Parent)
function App() {
const [count, setCount] = useState(0);
// Handlers for increment and decrement
const handleIncrement = () => setCount(count + 1);
const handleDecrement = () => setCount(count - 1);
return (
<div className="container card border-3 ">
<Counter
count={count}
onIncrement={handleIncrement}
onDecrement={handleDecrement}
/>
</div>
);
}
export default App;
Render and Test:
Run your app using
npm startand test the functionality of the increment and decrement buttons.

This code will create a basic React Counter App with styled buttons using Bootstrap. Let me know if you'd like further assistance!
Last updated