Only expressions, functions or classes are allowed as the default export

The error “Only expressions, functions or classes are allowed as the default export” occurs when we try to export by default like statements other than expression, function or classes in react. Let us take an example of the below code which throws the error.

// This code throws the error
export default const MyComponent = () => 
{
    return(
        <p>My Component</p>
    );
}

In the above code const MyComponent = () => is a statement in which we are declaring and initializing constant MyComponent. we are trying to export that statement which causes an error. 

The declaration and initialization of a variable is a statement that cannot be default export. When we export variables, we need to write them in two separate lines. First, define the variable and on another line, export it. You cannot define and default export a variable in a single line.

We can solve the error in the above sample code by splitting by defining and exporting a variable into two lines of code as given below.

const MyComponent = () => {
  	return(
        <p>My Component</p>
    );
}
 
export default MyComponent;

In the above code, we declared the arrow function, and then it can be exported by default at the bottom of the code.

We have another solution that uses regular javascript functions instead of arrow functions as given in the sample code.

export default function MyComponent(){
    return(
      <p>My Component</p>
  );
}

Here we have declared it as a regular javascript function instead of an arrow function. So it can be exported by default in the function declaration itself.

Conclusion

To solve the error “Only expressions, functions or classes are allowed as the default export”, write defining a variable and default export a variable in two separate lines. Use regular functions instead of arrow functions to make function declaration and export default in a single line.