1

I have a component where I use export default:

export default CategoryCard = (props) => {
    const {name, color, onPress } = props

    return (  ..my code 

and so the import statement is import CategoryCard.

When I try to run in the browser using Expo Client the browser returns error "ReferenceError: CategoryCard is not defined"

if I change export default CategoryCard to export const CategoryCard and change import CategoryCard to import { CategoryCard } then things work fine in browser.

I understand the difference between the statements and I am not overly concerned here as this is a native app that won't run in a browser ultimately - but I'm just curious for my own learning what is going on here and why the broswer doesn't like the export default.

1 Answers1

0

If you have something that's allowing you to do the version witout const (or let), then it's implemented modules incorrectly. The line

export default CategoryCard = (props) => {

says "Assign this value (an arrow function) to the already existing variable CategoryCard and export the value as the default export of this module." Modules are always in strict mode, so if you don't have a declaration for CategoryCard anywhere, that's a reference error. (Without strict mode, you can create globals by assigning to undeclared variables, but it's a Bad Idea™. :-) )

Since modules are always strict, you need that const or let in there:

export default const CategoryCard = (props) => {
// −−−−−−−−−−−−^^^^^

The browser giving you the error is correct, because it's a ReferenceError (in strict mode) to assign to an undeclared identifier.


Which isn't to say that you always have to have const or let or function or class with an export. You don't, you can export the result of an arbitrary expression as the default export. This is valid code, for instance:

export default 6 * 7;

So if you had CategoryCard declared elsewhere, your export would be valid:

let CategoryCard;
export default CategoryCard = (props) => {

I'm not suggesting that of course, just pointing out that it's valid. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875