0

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?

2
  • Format.prototype.formatDate is the function. class is sugar for prototypes. Commented Apr 5, 2016 at 2:18
  • "I created a small helper class:" You shouldn't be using a class for that. Just export the function: export default function formatDate() {}. Or if you have more such functions: export function formatDate() {}. Commented Apr 5, 2016 at 4:29

1 Answer 1

3

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';
Sign up to request clarification or add additional context in comments.

3 Comments

I like this approach better than using the prototype. It makes sense.
@SergioTapia don't fool yourself. class still makes use of prototypes. Class methods and instance methods are suited for different designs. They're both equally useful. class just hides away some of the ugly prototype syntax.
If you're just storing a set of functions, you might as well do export function formatDate(){} and import {formatDate} from '...'; and not use the class at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.