React/TypeScript - Type 'false | Element' is not assignable to type 'Element'

Viewed 1237

I am getting this error: Type 'false | Element' is not assignable to type 'Element'.

I am using React and TypeScript and the code looks like:

function App() {
    const [isSearching, setIsSearching] = useState(false);
    return (
        {isSearching && <div> Hey </div>}
    )
}

{isSearching && <div> Hey </div>} is giving the above error

Can anyone please help me point out what I may be missing here?

2 Answers

React component should return a JSX. If isSearching is false, you return false and no JSX.

This should fix the problem:

function App() {
    const [isSearching, setIsSearching] = useState(false);
    return (
        <>
          {isSearching && <div> Hey </div>}
        </>
    )
}

You must have forgotten return a value in your component.

function App() {
    const [isSearching, setIsSearching] = useState(false);

    return isSearching ? (<div> Hey </div>) : null
}
Related