Why is the keyword 'default' necessary when exporting a component withStyles

202 Views Asked by At

When I implement a simple React component with Mui's withStyles HOC, I have to use the keyword "default" when exporting the component. Why can't I use the HOC in the return statement within the functional component?

Is there something about Js or ReactJs that I'm missing?

Since I am forced to export this component as default, I lose the possibility to use the named import functionality, without using another import/export layer in between.

Below is the current working code:

// Card.js
import React from "react";
import {
  Card,
  withStyles
} from "@material-ui/core";

const styles = theme => ({
  card: {
    margin: theme.spacing(2)
  }
});

function CustomCard(props) {
  const {classes} = props;
  return (
    <Card className={classes.card}>
      Export me without being the default component.
    </Card>
  );
}

export default withStyles(styles)(MediaCard);

// Elsewhere.js
import CustomCard from "Card";
...

But i'd rather write something like this:

// Cards.js
import React from "react";
import {
  Card,
  withStyles
} from "@material-ui/core";

const styles = theme =\> ({
  card: {
    margin: theme.spacing(2)
  },
  anotherCard: {
    margin: theme.spacing(4)
  }
});

export function CustomCard(props) {
  const {classes} = props;
  return withStyles(styles)(
    <Card className={classes.card}>
      Jeah. I'm not the default component.
    </Card>
  );
}

export function AnotherCard(props) {
  const {classes} = props;
  return withStyles(styles)(
    <Card className={classes.anotherCard}>
      Jeah. I'm not the default component either.
    </Card>
  );
}

// Elsewhere.js
import { CustomCard, AnotherCard } from "Cards";
...
1

There are 1 best solutions below

0
Asplund On

You can do it the way you want to but you to change the way you define your components. The technical reason is that all exports except default need to be named, otherwise you can't import them and know what's what. Since withStyles() returns a statement and not a named variable/function you can't export it without a name.

export const AnotherCard = withStyles(styles)((props) => {
  const {classes} = props;
  return (
    <Card className={classes.anotherCard}>
      Jeah. I'm not the default component either.
    </Card>
  );
});

The downside of this is of course now your components aren't hoisted.