Search code examples
reactjsnpmnode-modulescreate-react-app

React createElement error "type is invalid -- expected a string got object"


I have facing this problem in a react project. I am using rc-upload package for uploading files in react. code is as below:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const Upload = require('rc-upload');

class App extends Component {
 constructor(props) {
 super(props);
 this.uploaderProps = {
    action: '/upload/',
    data: { user_id: 1 },
    headers: {
      Authorization: `Bearer abcdef`,
    },
    multiple: false,
    beforeUpload(file) {
      console.log(file);
    },
    onStart: (file) => {
      // console.log('onStart', file.name);
    },
    onSuccess(result) {
      console.log(result);
    },
    onProgress(step, file) {
      console.log('Progress: ', Math.round(step.percent), file.name);
    },
    onError(err) {
      // Show response data with close button in modal body
      console.log('onError', err);
    }
  };
 }
 render() {

  return (
   <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Welcome to React</h2>
    </div>
    <p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
    </p>
    <Upload {...this.uploaderProps}>Choose File</Upload>
   </div>
  );
 }
}
export default App;

This code is working in [email protected] and [email protected] and the dev dependencies of react or react-scripts. I created react app through create-react-app few months before. And now I created new app with create-react-app which installed with [email protected] and [email protected].

So when I run the above code in new project than it is showing this error.

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object

I figure out that it is coming from below code:

<Upload {...this.uploaderProps}>Choose File</Upload>

And it is working in my previous version of [email protected] but not in [email protected]

How to resolve this error? Is this a version error or any other dependency error?


Solution

  • Problem is related to how Upload component imported to the project. This might be a bug for the component. Don't know if this is intended or not but you need to import the component like this;

    const Upload = require('rc-upload').default;
    // or
    import Upload from 'rc-upload';