Reputation: 9823
I created a small helper class:
import moment from 'moment';
export default class Format {
formatDate(date) {
return moment(date);
}
}
And I'm trying to invoke it in a JSX template:
import React from 'react';
import Format from '/imports/helpers/format.js';
export default class ListingCard extends React.Component {
render() {
return (
<div className="card">
{Format.formatDate(this.props.listing.created_at)}</div>
</div>
)
}
}
Using WebStorm, the Format class is found. But the method is not.
ListingCard.jsx:22 Uncaught TypeError: _format2.default.formatDate is not a function
Any idea why?
Upvotes: 0
Views: 488
Reputation: 135217
You would need to use the static
keyword to declare a class method.
export default class Format {
static formatDate(date) {
return moment(date);
}
}
The reason for this is, if you do not use the static
keyword, formatDate
will be an instance method, meaning the method is only available on an instance of the class.
// e.g., how to use an instance method
var f = new Format();
f.formatDate(someDate);
@loganfsmyth makes a good remark; it's something I didn't think to address in my original answer.
If you don't plan on utilizing Format
as a class, there's no point in declaring it as such.
// format.js
import moment from 'moment'
export function formatDate(date) { return moment(date); }
// otherfile.js
import {formatDate} from './format';
Upvotes: 3