Search code examples
javascriptreactjsbuildcomponentsnwb

How do I include my custom Component using `require` instead of `include`


I have built a simple React Component using nwb as described in this guide.

It's a very simple Component that is just a button:

import t from 'prop-types'
import React, {Component} from 'react'

class LoadingButton extends Component {
  static propTypes = {
    disabled: t.bool,
    loading: t.bool,
    type: t.string,
  }
  static defaultProps = {
    disabled: false,
    loading: false,
    type: 'button',
  }
  render() {
    let {children, disabled, loading, type, ...props} = this.props
    if (loading) {
      disabled = true
    }
    return <button disabled={disabled} type={type} {...props}>
      {children}
    </button>
  }
}

export default LoadingButton

In another project, after using npm link, I am able to import this Component doing something like this:

import LoadingButton from 'react-loading-button'

And it works!

enter image description here

But my question is, I also need to include this Component using require (inside an older codebase). I would like to do something like this:

var LoadingButton = require("react-loading-button");

Unfortunately, this approach doesn't work for me. It gives me this error:

Error: Objects are not valid as a React child (found: [object Module]). If you meant to render a collection of children, use an array instead.

enter image description here

I have built the component using nwb, which states:

By default, nwb will create a CommonJS build for your project in lib/, which is the primary way it will be used when installed via npm, with default package.json main config pointing to lib/index.js.

So I am a bit confused about why the require doesn't work.

Has anyone had any experience with this approach?


Solution

  • I tried with function/class style components, var LoadingButton = require("react-loading-button").default; seems working fine, codebase is not exactly the same, but worth trying.