React - cannot be used as a JSX component. Its return type 'void' is not a valid JSX element

Viewed 29528

I have a stackblitz demo here

It's a super simple app that should just show an input with test below and the output of whats been put into the input field.

I'm getting an error on the input component

'CustomInput' cannot be used as a JSX component.
  Its return type 'void' is not a valid JSX element.

Can anyone see why I'm getting this error

2 Answers

You need to add parenthesis after return:

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return (
    <div>
      <label htmlFor="search">{children}</label>
      <input id="search" type="text" value={value} onChange={onChange} />
    </div>
  )
}

https://stackblitz.com/edit/react-ts-pb6jpc?embed=1&file=index.tsx


If you are writing

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return 
    <div>
      <label htmlFor="search">{children}</label>
      <input id="search" type="text" value={value} onChange={onChange} />
    </div>
}

this is transformed as

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return;
    <div>
      <label htmlFor="search">{children}</label>
      <input id="search" type="text" value={value} onChange={onChange} />
    </div>
}

so you function basically returns undefined and is interpreted as

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return undefined;
  // nothing after return counts
}

A better way of defining the types for props is :

const CustomInput:React.FC<CustomInputProps> = ({children, value, onChange}) => {
  return  (
    <div>
      <label htmlFor="search">{children}</label>
      <input id="search" type="text" value={value} onChange={onChange} />
    </div>
  )
}
Related