new Date().getFullYear() in React
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.
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);