Ankit Prakash
Ankit Prakash

Reputation: 85

How to display working digital clock using React

I want to render digital clock on the browser , i don't know where to use setInterval() function in my script and also the what will be the name of function used as a first argument.

<!DOCTYPE html>
    <html>
    <head>
        <title>My First App</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
    </head>
    <body>
    <div id="react-app"></div>
    <div id="clock-box"></div>

    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>

    <script type="text/jsx">

    class StoryBox extends React.Component{
            render(){
                return(<div> Hello World </div> );
            }
        }
    var target= document.getElementById('react-app');
    var clockTarget=document.getElementById('clock-box');
    ReactDOM.render(<StoryBox/>,target)

    class ClockFunction extends React.Component{
        render(){
            return(<div>
                <h1>Digital Clock</h1>
                <h2>
                {
                    new Date().toLocaleTimeString() 
                    }
                </h2>
            </div>) ;
        }
    }

    ReactDOM.render(<ClockFunction />,clockTarget);

    </script>

    </body>
    </html>

Upvotes: 5

Views: 12319

Answers (7)

Sky
Sky

Reputation: 2609

Using react hooks:

import {useEffect, useState} from "react";

export default function Clock() {

const [time, setTime] = useState(new Date().toLocaleTimeString())

useEffect(() => {
    const id = tick()
    return () => clearTimeout(id)
}, [])


const tick = () => {
    return setInterval(() => {
        setTime(() => new Date().toLocaleTimeString())
    }, 1000)
}

return (
    <p>Current time: {time}</p>
)

}

Upvotes: 0

ZFS STUDIO
ZFS STUDIO

Reputation: 1

Within few steps We can display Digital clock easily, Lets use class component and toLocaleTimeString() method which returns time.

Let's begin

import React from 'react'

class Clock extends React.Component{
     state = {time: ''};
     componentDidMount(){
          setInterval(
          () => this.setState({time: new Date().toLocaleTimeString()},1000)
          )

    }
    render(){
        return(
            <div>{this.state.time}</div>
        )
    }
}

Upvotes: 0

Daniyor Boltaev
Daniyor Boltaev

Reputation: 11

    const MyClock = () => {
  const [time, setTime] = useState(new Date());
   useEffect(() => {
     let TimeId = setInterval(() => setTime(new Date()), 1000);
     return () => {
      clearInterval(TimeId);
     };
     });

      return <div > itis {
          time.toLocaleTimeString()
  } < /div>;
 };

Upvotes: 0

Azzam Jihad Ulhaq
Azzam Jihad Ulhaq

Reputation: 111

import React, { Component } from "react";

class Clock extends Component {
    constructor (props) {
        super(props);

        this.state = {
            dateClass: new Date()
        }

        this.time = this.state.dateClass.toLocaleTimeString();
        this.hourMin = this.time.length === 10? this.time.slice(0) : this.time.slice(0,5);
    }

    setTime = () => {
        this.setState({
            dateClass: new Date()
        })
        this.time = this.state.dateClass.toLocaleTimeString();
        this.hourMin = this.time.length === 10? this.time.slice(0) : this.time.slice(0,5);
    }

    componentDidMount () {
        setInterval(this.setTime, 1000)
    }
    
    render () {
        return (
            <div>
                {this.hourMin}
            </div>
        )
    }
}

export default Clock;

May be you can try this approach.

Upvotes: 1

vikas kumar
vikas kumar

Reputation: 53

// A very simple React Digital clock

    class App extends React.Component {
        componentDidMount() {
            setInterval(() => {
                this.getTime();
            })
        }
        constructor() {
            super();
            this.state = {
                time: "00:00:00:AM",
            }
        }
        getTime() {
            setInterval(() => {
                let date = new Date();
                let hour = date.getHours();
                let minute = date.getMinutes();
                let seconds = date.getSeconds();
                let ampm = this.hour >= 12 ? 'AM' : 'PM';
                hour = hour % 12;
                hour = hour ? hour : 12;
                hour = fullTime(hour);
                minute = fullTime(minute);
                seconds = fullTime(seconds); 
                this.setState({
                    time: hour % 12 + ":" + minute + ":" + seconds + ":" + 
                 ampm,
                });
                function fullTime(n) { return n < 10 ? "0" + n : n }

            }, 1000);
        }
        render() {
            return (
                <div className="container">
                    <h3>{this.state.time}</h3>
                </div>
            );
        }
    };

    ReactDOM.render(<App />, document.querySelector("#root"));

Upvotes: 0

Aron
Aron

Reputation: 9248

For this you're going to need a few things:

  1. a setInterval to update the time
  2. a variable in the component's state for keeping track of the time
  3. a safe way of adding and removing the setInterval when the component mounts and unmounts respectively

This component will do all of those things:

class ClockFunction extends React.Component {

    constructor() {
        super();
        this.state = { time: new Date() }; // initialise the state
    }

    componentDidMount() { // create the interval once component is mounted
        this.update = setInterval(() => {
            this.setState({ time: new Date() });
        }, 1 * 1000); // every 1 seconds
    }

    componentWillUnmount() { // delete the interval just before component is removed
        clearInterval(this.update);
    }

    render() {
        const { time } = this.state; // retrieve the time from state

        return (<div>
            <h1>Digital Clock</h1>
            <h2>
                {/* print the string prettily */}
                {time.toLocaleTimeString()}
            </h2>
        </div>);
    }
}

Upvotes: 9

Umang Gupta
Umang Gupta

Reputation: 16440

class ClockFunction extends React.Component{
    //setInterval and setState go in component Did mount
    componentDidMount (){
    this.setState({time : (new Date()).getTime()}
    // update every second
    this.tick = setInterval( () => this.setState(time : this.state.time + 1000, 1000)
    }

    //use state to display time in render function
    render(){
        return(<div>
            <h1>Digital Clock</h1>
            <h2>
            {
                this.state.time
            }
            </h2>
        </div>) ;
    }
}

Upvotes: 0

Related Questions