Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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

like image 406
lomine Avatar asked Dec 23 '22 16:12

lomine


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
}
like image 63
strdr4605 Avatar answered May 06 '23 14:05

strdr4605


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>
  )
}
like image 40
Gayatri Dipali Avatar answered May 06 '23 16:05

Gayatri Dipali