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

前端 未结 30 1621
孤城傲影
孤城傲影 2020-11-22 06:53

I am getting this error:

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/funct

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 07:32

    I've discovered another reason for this error. It has to do with the CSS-in-JS returning a null value to the top-level JSX of the return function in a React component.

    For example:

    const Css = styled.div`
    
    `;
    export function exampleFunction(args1) {
      ...
      return null;
    }
    
    export default class ExampleComponent extends Component {
    ...
    render() {
    const CssInJs = exampleFunction(args1);
      ...
      return (
        
          
          ...
        
      );
    }
    

    I would get this warning:

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

    Followed by this error:

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

    I discovered it was because there was no CSS with the CSS-in-JS component that I was trying to render. I fixed it by making sure there was CSS being returned and not a null value.

    For example:

    const Css = styled.div`
    
    `;
    export function exampleFunction(args1) {
      ...
      return Css;
    }
    
    export default class ExampleComponent extends Component {
    ...
    render() {
    const CssInJs = exampleFunction(args1);
      ...
      return (
        
          
          ...
        
      );
    }
    

提交回复
热议问题