In this blog you will learn to code timer app using javascript and react.
Step 1: Setup React Project
- Install Node.js and npm (Node Package Manager) if you haven’t already.
- Open your command prompt or terminal and navigate to the desired directory for your project.
- Run the following command to create a new React project:
npx create-react-app digital-watch
The command npx create-react-app digital-watch
creates a new directory named digital-watch
with the necessary project files and dependencies.
- Navigate into the project directory:
cd digital-watch
- Open the project in your preferred code editor.
Step 2: Create the Watch Functional Component
- In the “src” directory, create a new file called “Watch.js”.
- Open “Watch.js” and add the following code:
import React, { useState, useEffect } from "react";
const Watch = () => {
const [time, setTime] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setTime(new Date());
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div className="watch">
<h1>{time.toLocaleTimeString()}</h1>
</div>
);
};
export default Watch;
The Watch
component is responsible for displaying the current time.
It uses React hooks, specifically useState
and useEffect
, which are functions provided by React to manage state and handle side effects.
The time
state variable holds the current time, and setTime
is a function to update the time
state.
The useEffect
hook is used to run code when the component is mounted (first rendered) and when it is unmounted (removed from the screen).
Inside the useEffect
hook, an interval is set up using setInterval
to update the time every second by calling setTime(new Date())
.
The Watch
component renders the current time inside an <h1>
element.
Step 3: In Index.js add the following code.
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
createRoot(document.getElementById("root")).render(<App />);
In index.js
file as you can see this renders the <App />
component in element with id root in index.html
file
Step 4: Update App Component
- Open “App.js” in the “src” directory.
- Clear the existing code and replace it with the following code:
import React from "react";
import Watch from "./Watch";
import "./App.css";
const App = () => {
return (
<div className="app">
<div className="website-url">
<a href="https://codingissimple.com">Coding is Simple</a>
</div>
<Watch />
</div>
);
};
export default App;
- The
App
component is the main component of the application. It imports theWatch
component and a CSS file for styling. Inside theApp
component, there is a<div>
element with the classwebsite-url
, which contains a link to a website. TheWatch
component is rendered below the website URL inside another<div>
element.