'react-native-webview Typescript error: 'WebView' cannot be used as a JSX component
I am trying to set up a simple React Native app using Expo with TypeScript that shows a WebView. My App.tsx
file contains the following:
import Constants from 'expo-constants';
import { StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';
export default function App() {
return (
<WebView
style={styles.container}
source={{ uri: 'https://example.com/' }}
/>
);
}
const styles = StyleSheet.create({
container: {
marginTop: Constants.statusBarHeight,
},
});
This code works correctly, but the TypeScript compiler throws an error at the WebView component.
App.tsx:7:4 - error TS2786: 'WebView' cannot be used as a JSX component.
Its instance type 'WebView<{ style: { marginTop: number; }; source: { uri: string; }; }>' is not a valid JSX element.
The types returned by 'render()' are incompatible between these types.
Type 'import("C:/example/node_modules/@types/react/index").ReactNode' is not assignable to type 'React.ReactNode'.
Type '{}' is not assignable to type 'ReactNode'.
Type '{}' is missing the following properties from type 'ReactPortal': key, children, type, props
7 <WebView
~~~~~~~
Found 1 error.
I am using the following versions of my dependencies:
{
"dependencies": {
"expo": "~44.0.0",
"expo-status-bar": "~1.2.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-native": "0.64.3",
"react-native-web": "0.17.1",
"react-native-webview": "11.15.0"
},
"devDependencies": {
"@babel/core": "^7.12.9",
"@types/react": "~17.0.21",
"@types/react-native": "~0.64.12",
"typescript": "~4.3.5"
}
}
How can I correct this error?
Solution 1:[1]
You would get this error if you had more than one @types/react
library in your node_modules
. In my case this was caused by Storybook which included @reach/router which included @types/reach__router which included @types/react@18 different from my current Expo version.
Using How do I override nested dependencies with `yarn`?
I added the matching version
"resolutions": {
"@types/react": "~17.0.21"
},
and regenerated to get rid of the error.
Solution 2:[2]
Some libraries don't support typescript. In this case you can use the comment
// @ts-ignore
in front of the error to let TS ignore it.
Solution 3:[3]
You can try like that:
const App: FC = () => {
return (
<WebView
style={styles.container}
source={{ uri: 'https://example.com/' }}
/>
);
}
export default App;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Archimedes Trajano |
Solution 2 | Maximilian Dietel |
Solution 3 | Marat |