Given a React component within a Next.js application that has a sub-section that can be set to something, or not, storing it in a variable like this:
export const MyComponent = (): JSX.Element => {
let [result, setResult] = useState<ReactNode>()
async function doFetch() {
// ... await some API call
setResult('Successful result!')
}
return (
<div>
<button onClick={doFetch}>Go</button>
{ result }
</div>
)
}
The ReactNode
type allows for the variable to be a JSX element, a string, or null
/undefined
. However, the curly-brace insertion gets typed as Element
, and I get an error that ReactNode
cannot be assigned to an Element
type, because undefined
cannot be cast to a ReactElement<any, any>
type.
The error is appearing in my Visual Studio IDE, and when doing a npx next build
with the library dependencies of:
"@types/react": "18.0.20",
"@types/react-dom": "18.0.6",
"next": "12.3.1",
"react": "18.2.0",
"react-dom": "18.2.0"
"typescript": "4.8.3"
Is my type-setting on useState
wrong? Or is something misconfigured that is forcing inline-expressions to be Element
types (non-null) versus ReactNode
types?
Answers on other React/Typescript questions like https://stackoverflow.com/a/72353143/144756 imply the type of an inline expression should be ReactNode
, but my setup is declaring it as Element
. Did something change with a recent version of React or Next?