Trouble Getting Class to Render in App.js

Viewed 30

I am having some trouble trying to get this clock component to render in my App.js. My App.js looks like this:

function App(){
    return ( 
      <div>
      <Header/>
        <h1>
           ...
        </h1>  
      <Footer/>
    </div>      
  );
}
export default App;

I would like to get this clock to display a constantly updating time which it does on its own. I am not sure how to call it from App.js without running into DOM or root errors. Any advice would be appreciated!

import ReactDOM from 'react-dom';

class Clock extends React.Component {
    constructor(props) {
      super(props);
      this.state = {date: new Date()};
    }
  
    componentDidMount() {
      this.timerID = setInterval(
        () => this.tick(),
        1000
      );
    }
  
    componentWillUnmount() {
      clearInterval(this.timerID);
    }
  
    tick() {
      this.setState({
        date: new Date()
      });
    }
  
    render() {
      return (
        <div>
          <h2>It is {this.state.date.toUTCString()}</h2>
        </div>
      );
    }
  }

  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(<Clock />);
1 Answers

You reference the Clock component from your App component, as below. The App component is what you render to the actual DOM.

Sandbox: https://codesandbox.io/s/reverent-jang-63jq5p

Clock.js

import * as React from "react";

export class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h2>It is {this.state.date.toUTCString()}</h2>
      </div>
    );
  }
}

App.js

import "./styles.css";
import { Clock } from "./Clock";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Clock />
    </div>
  );
}

index.js

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);
Related