2

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.

5
  • What happens if you remove 'string' from type? Commented Nov 19, 2019 at 11:45
  • You can use return <value /> Commented Nov 19, 2019 at 11:45
  • @kinduser Nothing happens. Commented Nov 19, 2019 at 11:47
  • @RaminRezazadeh A component has to be capitalized. Commented Nov 19, 2019 at 11:47
  • What you have looks like a functional component, would it be alright to use your function as a functional component? const RenderValue? Commented Nov 19, 2019 at 11:57

1 Answer 1

1

<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>
  )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Just edited the answer, if value is not valid element just render string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.