energ1ser
energ1ser

Reputation: 2873

ReactJS export const and component from one module

I have two modules that I want to share a const array. One of these modules includes both the const array and a component, whilst the other module only includes a component.

This is what I have in module "A".

export const ORDER_COLUMNS = [
  { name: 'orderNumber', title: 'Order', width: '10%',  type: 'string' },
  { name: 'orderType', title: 'Type', width: '10%',  type: 'string' }
];

class OrderGridControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        orderColumns: ORDER_COLUMNS
    };
  }
  ...

}

export default OrderGridControl;

And in module "B".

import {OrderGridControl, ORDER_COLUMNS} from 'component/order-grid-control';

class OrderQueryPage extends React.Component {
      constructor(props) {
    super(props);
    this.state = {
        orderColumns: ORDER_COLUMNS
    };
    console.info(this.state.orderColumns);
  }

  ...

  render() {
    return (
      <div>
        <PropertyGrid gridSetup={this.state.orderColumns} />
      </div>
    );
  }
}

When I run this I get the following error. invariant.js:39 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'moduleB'.

However, the console.info(this.state.orderColumns) line logs all the column objects I expect.

Interestingly, if I copy the array into module "B" and assign the columns in the constructor exactly the same way it seems to work. It only seems to be an issue when I'm importing from the other module.

Upvotes: 5

Views: 30822

Answers (1)

Interrobang
Interrobang

Reputation: 17434

You've got it almost right-- you're exporting a default export (OrderGridControl) and a named export (ORDER_COLUMNS).

However, in B.js, you're trying to import two named exports.

Modify your import to look like this:

import OrderGridControl, { ORDER_COLUMNS } from 'component/order-grid-control';

The advantage of having a default export is that you don't have to match its name exactly when importing it, so you could do something like

import GridControl, { ORDER_COLUMNS } from 'component/order-grid-control';

Upvotes: 9

Related Questions