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()?
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.
getFullYear() The getFullYear() method returns the year of the specified date according to local time.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With