Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

I wrote some code:

function renderGreeting(Elem: React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

I'm getting an error:

JSX element type Elem does not have any construct or call signatures

What does it mean?

like image 459
Ryan Cavanaugh Avatar asked Oct 02 '22 07:10

Ryan Cavanaugh


People also ask

What is JSX element type?

JSX is an embeddable XML-like syntax. It is meant to be transformed into valid JavaScript, though the semantics of that transformation are implementation-specific. JSX rose to popularity with the React framework, but has since seen other implementations as well.

What is a JSX attribute?

Attributes in JSX: JSX allows us to use attributes with the HTML elements just like we do with normal HTML. But instead of the normal naming convention of HTML, JSX uses camelcase convention for attributes. For example, class in HTML becomes className in JSX.

Is not defined React JSX no undef?

The React. js error "X is not defined react/jsx-no-undef" occurs when we forget to import a function, class or a variable in our code before using it. To solve the error, make sure to import the value before using it in your code, e.g. import {myFunc} from 'my-package' .

How do you pass components as props React?

You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop.


1 Answers

This is a confusion between constructors and instances.

Remember that when you write a component in React:

class Greeter extends React.Component<any, any> {
    render() {
        return <div>Hello, {this.props.whoToGreet}</div>;
    }
}

You use it this way:

return <Greeter whoToGreet='world' />;

You don't use it this way:

let Greet = new Greeter();
return <Greet whoToGreet='world' />;

In the first example, we're passing around Greeter, the constructor function for our component. That's the correct usage. In the second example, we're passing around an instance of Greeter. That's incorrect, and will fail at runtime with an error like "Object is not a function".


The problem with this code

function renderGreeting(Elem: React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

is that it's expecting an instance of React.Component. What you want is a function that takes a constructor for React.Component:

function renderGreeting(Elem: new() => React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

or similarly:

function renderGreeting(Elem: typeof React.Component) {
    return <span>Hello, <Elem />!</span>;
}
like image 342
Ryan Cavanaugh Avatar answered Oct 16 '22 09:10

Ryan Cavanaugh