Let's say my react.js app is going to display dates and I would like to apply the format that is set in the client's browser/OS. There are multiple components that show dates and I can use a couple of ways to share the code between them.
1.Re-usable React.js components like:
var React = require('react');
module.exports = React.createClass({
render : function(){
if(this.props.value === null || this.props.value===undefined)
return false;
var formattedValue = new Date(this.props.value).toLocaleDateString();
return(
<span>
{formattedValue}
</span>
);
}
});
and then use them like:
var DateFormatter = require('./../formatters/Date');
<DateFormatter value={invoice.date} />
2.Utility functions shared via React.js mixins, ie:
module.exports = {
renderDate : function(dateValue){
if(dateValue === null || dateValue===undefined)
return false;
var formattedValue = new Date(dateValue).toLocaleDateString();
return(
<span>
{formattedValue}
</span>
);
}
}
and then just add the mixin to a component and use something like
{this.renderDate(invoice.date)}
To me it seems that there is no much difference between these 2 approaches for now. But I would love to hear the opinion of community about pros and cons of each solution. TIA!
One aspect is performance: if you write a component to display the date like you did above, you can mark it with PureRenderMixin , as the rendered output relies only on the the props. This might speed up the rendering a bit, as the formatting only needs to be done when the date changes.
From clean code point of view, I would either write a component or use a non-react utility function that just formats the date to a string - no need to couple the date formatting and dom elements. Something like:
function formatDate(dateValue){
if(dateValue == null)
return ""
return new Date(dateValue).toLocaleDateString()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.