Reputation: 34093
I have a function that conditionally renders/returns a string or a dynamic component depending on what type the prop is:
const renderValue = (value: string | React.ReactNode) => {
if (React.isValidElement(value)) {
const Component = value
return <Component />
}
return value
}
However, with the above code I get the following message from Typescript:
JSX element type 'Component' does not have any construct or call signatures.ts(2604)
I have read other answers on this topic on SO, but still haven't concluded an answer.
Upvotes: 2
Views: 2342
Reputation: 238
<Component />
is JSX notation and it's basically telling React to render this component. That's only possible in React Component
which has to return JSX code. To solve the problem you could just check if argument is valid element and then render it conditionally in desired React Component
import React from 'react'
interface Props {
value: string | React.ReactNode
}
const SomeComponent:React.FC<Props> = ({value}) => {
return (
<div>
<span>Hello World</span>
{React.isValidElement(value) ? <Component/> : value}
</div>
)
}
Upvotes: 1