Search code examples
reactjsreact-lifecycle

How can I define a method inside a class component in React?


I have made a simple digital clock in React. It seems working. However, I wanted to define the callback function inside the setState() separately. But I got an error. Do you know how I can define such a function called tick() outside the componenDidMount? Below is my code

import "./Clock.css";

class Clock extends React.Component {
    state = { date: new Date() };

    componentDidMount() {
        setInterval(() => {
            this.setState({ date: new Date() });
        }, 1000);
        console.log("componentdidmount");
    }

    render() {
        return (
            <div className="clock-container">
                <h1 className="clock">{this.state.date.toLocaleTimeString()}</h1>
            </div>
        );
    }
}

export default Clock;

Solution

  • Is this what you want it to be like?

    tick(){
        this.interval = setInterval(() => {
            this.setState({ date: new Date() });
        }, 1000);
    }
    
    componentDidMount() {
        this.tick();
        console.log('componentdidmount');
    }
    
    componentWillUnmount(){
        clearInterval(this.interval);
    }