I'm trying to learn some of the new features in React 18, such as the SuspenseList
and new useId
hook, but I seem to be getting the same error over and over:
Module '"react"' has no exported member 'SuspenseList'. TS2305
This is what my package.json looks like:
"dependencies": {
"bootstrap": "^5.1.1",
"history": "^5.0.1",
"react": "^18.0.0-rc.0",
"react-dom": "^18.0.0-rc.0",
"react-error-boundary": "^3.1.3",
"react-router-dom": "^6.0.0-beta.5",
"swr": "^1.0.1",
"web-vitals": "^1.1.2"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"@types/jest": "^26.0.24",
"@types/node": "^12.20.27",
"@types/react": "^17.0.37",
"@types/react-dom": "^17.0.9",
"prettier": "^2.4.1",
"react-scripts": "4.0.3",
"typescript": "^4.4.3"
},
I have no clue what to do at this point, as I've installed the RC version of React 18, which should be the latest according to the Working Group GitHub discussion board.
CodePudding user response:
You're getting that error from the TypeScript compiler because, even though you've installed react@next
, you're still using @types/react@17
. SuspenseList
does exist in the implementation, but the compiler doesn't know that.
Although there's no equivalent @types/react@next
install, @types/react
does include:
next.d.ts
(types which will definitely be in v18); andexperimental.d.ts
(types which are currently in experimental builds).
The source code of the latter (as SuspenseList
and the whole concurrent mode API is still experimental) tells you how to use these types in a project:
These are types for things that are present in the
experimental
builds of React but not yet on a stable build.Once they are promoted to stable they can just be moved to the main index file.
To load the types declared here in an actual project, there are three ways. The easiest one, if your
tsconfig.json
already has a"types"
array in the"compilerOptions"
section, is to add"react/experimental"
to the"types"
array.Alternatively, a specific import syntax can to be used from a TypeScript file. This module does not exist in reality, which is why the
{}
is important:import {} from 'react/experimental'
It is also possible to include it through a triple-slash reference:
/// <reference types="react/experimental" />
Either the import or the reference only needs to appear once, anywhere in the project.