How to fix Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

Dennis picture Dennis · Oct 29, 2018 · Viewed 16.8k times · Source

I am trying to run ReactRails app and trying to run a very simple react-select component. However, in the same file if I print just a simple h2 element it works but <Select/> doesn't work. It gives:

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

I am trying to use react-select component. I've installed it via yarn add command.

User.jsx:

var React = require("react")
var Select = require("react-select")
var PropTypes = require("prop-types")

// also tried these ->
// import React from 'react';
// import createClass from 'create-react-class';
// import PropTypes from 'prop-types';
// import Select from 'react-select';


const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
];

class User extends React.Component {
  state = {
    selectedOption: null,
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  }
  render() {
    const { selectedOption } = this.state;

    /*
    return (
             <h2>THIS WORKS!</h2>
    )
    */



    return (
             <Select
                 value={selectedOption}
                 onChange={this.handleChange}
                 options={options}
             />
    )

    // Doesn't work:
    // Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

  }
}
module.exports = User

I am very new to React world. What Am I missing here? What am I doing wrong?

Note: This did not solved my problem: Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Answer

seanulus picture seanulus · Oct 29, 2018

I'm not sure how the module.exports plays with React. When I try your code with ES6 syntax it seems to work fine.

import React from 'react';
import Select from 'react-select';

and then using ES6 export instead of module.exports:

export default User;

The Select component doesn't seem to be the issue.