简体   繁体   中英

Render prop as string or component with Typescript

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.

<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>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM