zamf
zamf

Reputation: 35

React JS clock compo

I want to make clock made of components in react. Each value I want to be from different components. I got that code:

import React from 'react';
import ReactDOM from 'react-dom';

class ClockTimeHour extends React.Component{
  render(){
    return <h1>{this.props.date.getHours()}</h1>
  }
}

class ClockTimeMinute extends React.Component{
  render(){
    return <h1>{this.props.date.getMinutes()}</h1>
  }
}

class ClockTimeSecond extends React.Component{
  render(){
    return <h1>{this.props.date.getSeconds()}</h1>
  }
}

class ClockDateYear extends React.Component{
  render(){
    return <h1>{this.props.date.getFullYear()}</h1>
  }
}

class ClockDateMonth extends React.Component{
  render(){
    return <h1>{this.props.date.getMonth()}</h1>
  }
}

class ClockDateDay extends React.Component{    
  render(){
    return <h1>{this.props.date.getDate()}</h1>
  }
}

class ClockTime extends React.Component{

  render(){
    return (
      <div>
        <ClockTimeHour date={this.state.now}/>
        <ClockTimeMinute date={this.state.now}/>
        <ClockTimeSecond date={this.state.now}/>
      </div>
    );
  }
}

class ClockDate extends React.Component{
  render(){
    return (
      <div>
        <ClockDateYear date={this.state.now}/>
        <ClockDateMonth date={this.state.now}/>
        <ClockDateDay date={this.state.now}/>
      </div>
    );
  }
}

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

  componentDidMount() {
    this.timerId=setInterval(()=>{
      this.setState({ now : new Date() });
    },1000);
  }

  render(){
    return (
      <div>
        <ClockTime date={this.state.now}/>
        <ClockDate date={this.state.now}/>
      </div>
    );
  }
}

document.addEventListener('DOMContentLoaded', function(){
    ReactDOM.render(
        <Clock/>,
        document.getElementById('app')
    );
});

and when I am running it I got: Uncaught TypeError: Cannot read property 'now' of null at ClockTime.render

Upvotes: 1

Views: 97

Answers (1)

Facundo La Rocca
Facundo La Rocca

Reputation: 3866

You are not setting the state for the component you mentioned, but your are passing through it props as date here <ClockTime date={this.state.now}/>, so I assume you might want to change from:

class ClockTime extends React.Component{
  render(){
    return <div>
    <ClockTimeHour date={this.state.now}/>
    <ClockTimeMinute date={this.state.now}/>
    <ClockTimeSecond date={this.state.now}/>
    </div>
  }
}

to:

class ClockTime extends React.Component{
  render(){
    return (
      <div>
        <ClockTimeHour date={this.props.date}/>
        <ClockTimeMinute date={this.props.date}/>
        <ClockTimeSecond date={this.props.date}/>
      </div>
    );
  }
}

You can find here a working example, using your code but applying the changes I've seggested.

Upvotes: 1

Related Questions