Ray Erd
Ray Erd

Reputation: 63

See date on button click in react

The below code not showing the expected output of current date and time

class Mydate extends React.Component{
  constructor(props){
    super(props);
    this.state={
      date:new Date(),
      showMessage: false
    }
    this.show=this.show.bind(this);
  }
  show(){
    this.setState({showMessage: true});
    return this.state.date;  
  }
  render(){
    return(
      <div>
        <h2>Hello World!!</h2>
         {this.state.showMessage && <p>{this.state.date}</p>}
        <button onClick={this.show}>show Date</button>
      </div>
    );
  }
}
    

why show() doesnt work here.Can you please help me to know where is the issue

Upvotes: 2

Views: 2136

Answers (2)

GBourke
GBourke

Reputation: 1963

currently, the date object is being rendered as an object within the <p> tag. Objects cannot be passed as "children" to jsx tags.

A minimal fix would be to convert the date to string using toString() method when displaying the date within the <p> tag.

   render(){
    return(
      <div>
        <h2>Hello World!!</h2>
         {this.state.showMessage && <p>{this.state.date.toString()}</p>} 
        <button onClick={this.show}>show Date</button>
      </div>
    );
  }

https://codesandbox.io/s/focused-smoke-vtiyf?file=/src/App.js:511-522

I hope this helps.

Cheers

Upvotes: 0

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

As i checked this.state.date is an js Date object, when it's printing in the document its tying to convert it to string to make sure its a valid children in jsx, and gets fails. use something as below

<p>{this.state.date.toString()}</p>

Demo

Upvotes: 2

Related Questions