Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Date().getFullYear() in React

I'm trying to display a current year in footer and trying to figure out how to get the current year React way? Is there a way to use new Date().getFullYear()?

like image 713
Max T Avatar asked Dec 22 '16 23:12

Max T


People also ask

What is new date () in react?

Use the Date() constructor to get the current year in React, e.g. new Date(). getFullYear() . The getFullYear() method will return a number that corresponds to the current year.

What is getFullYear () in JavaScript?

getFullYear() The getFullYear() method returns the year of the specified date according to local time.


2 Answers

You need to put the Pure JavaScript inside {}. This works for me:

class HelloMessage extends React.Component {   render() {     return <div>{(new Date().getFullYear())}</div>;   } }  ReactDOM.render(<HelloMessage />, mountNode); 

The compiled version is:

class HelloMessage extends React.Component {   render() {     return React.createElement(       "div",       null,       new Date().getFullYear()     );   } }  ReactDOM.render(React.createElement(HelloMessage, null), mountNode); 
like image 110
Praveen Kumar Purushothaman Avatar answered Sep 22 '22 02:09

Praveen Kumar Purushothaman


One thing you could do is create a function outside of the render function that gets the year:

getYear() {     return new Date().getFullYear(); } 

and then insert it into the render function wherever you would like. For instance, you could put it in a <span> tag to get the current year in your footer:

<span>    © {this.getYear()} Your Name </span> 

Which would produce:

© 2018 Your Name

With a well-named function outside of the render method, you can quickly find what the function does and you have the ability to modify it in the future if, say, you want to change the copyright year such as © 1996 - 2018, etc.

like image 21
juanezamudio Avatar answered Sep 25 '22 02:09

juanezamudio