SPG
SPG

Reputation: 6197

TypeScript: How to define the type when pass component in props in React?

Here's the code sample and the JS version is working correctly.

The issue I encountered happening in TS :

import React from 'react'

class Parent extends React.Component {
    render() {
      return (
        <Child Cpnt={<Header title='Header' />} />
        /* TS error on Cpnt */
      )
    }
  }

interface ChildProps {
    Cpnt: React.ComponentClass
}

class Child extends React.Component <ChildProps> {
    render () {
        const { Cpnt } = this.props
        return (
            <div>
                {{Cpnt}}
            </div>
        )
    }
}

interface HeaderProps {
    title: string
}

class Header extends React.Component <HeaderProps> {
    render () {
        const { title } = this.props
        return (
            <p>{title}</p>
        )
    }
}

I got an error on <Child Cpnt

[ts]
Type 'Element' is not assignable to type 'ComponentClass<{}, any>'.
  Type 'Element' provides no match for the signature 'new (props: {}, context?: any): Component<{}, any, any>'. [2322]

What type should I defind here?

Upvotes: 4

Views: 3472

Answers (2)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175088

A React "renderable" is not React.ComponentClass but React.ReactNode.

Ask for React.ReactNode in your Cpnt prop.

Upvotes: 6

ManavM
ManavM

Reputation: 3108

You are passing <Header title='header' /> which is a React Element not Header which is a Component Class.

Upvotes: 0

Related Questions