Arnaud
Arnaud

Reputation: 750

Can't import React component on server-side Next.js

I'm trying to import a very simple component from a library into a Next.js app.

I have stripped down my library to the bare minimum. It contains the following src/components/index.js:

import React from 'react'
const Container = ({ children }) => <div>{children}</div>
export { Container }

In my Next.js app, I created a pages/index.js that contains the following:

import React from 'react'
import { Container } from 'mylib'

class HomePage extends React.Component {
  render() {
    return <Container>Hello</Container>
  }
}

export default HomePage

mylib is a local npm package which I have installed in my Next.js app using npm i ../mylib. It has a standard webpack config:

const path = require('path')

module.exports = {
  entry: {
    components: './src/components/index.js',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
    libraryTarget: 'commonjs2'
  },
  mode: "production",
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        }
      }
    ],
  },
};

and then the package.json points to dist/components.js as the main file.

The following does work:

  1. In my Next.js app, replace return <Container>Hello</Container> with return <div>Hello</div> (while keeping the import { Container } in place)
  2. Refresh the page in the server (I'm running Next's dev server)
  3. Restore the use of <Container> (the opposite of step 1)
  4. Save the file --> hot-reload in the browser with the Container properly displayed (I added a className to be sure)

At this point, if I refresh the browser, I get the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

which suggests I made a bad import/export, but I don't know where. And the error only occurs on the server-side.

What did I do wrong?

Upvotes: 3

Views: 2460

Answers (1)

DJNorris
DJNorris

Reputation: 95

Container should be a default export, so this:

import React from 'react'

const Container = ({ children }) => <div>{children}</div>

export { Container }

should be this:

import React from 'react'

const Container = ({ children }) => <div>{children}</div>

export default Container

You could also one-line the Container component like this:

import React from 'react'

export default Container = ({ children }) => <div>{children}</div>

Upvotes: -1

Related Questions