Closed tburnt closed 2 years ago
I get the same error in my project. @tburnt Did you find a solution to work around the problem?
I get the same error in my project. @tburnt Did you find a solution to work around the problem?
nope I am still burning my candles with this one among all other problems
@tburnt I've found the source of the problem. There should be always NativeBaseProvider component at the root of Native Base components tree. In my case this component was not the root.
Same error after ugprading to 3.2.2 from 2.15.2. I am using react navigation and not sure where to put NavtiveBaseProvider since react navigation has a root component which is already in App.js.
I have the same problem "native-base": "^3.2.2", "react": "17.0.2", "react-native": "0.66.3",
I had the same issue since yesterday. The problem was when I create a new app project, I restructured its folder and sub-components. Because of that, I forgot to change the root component's import location in "index.js". I was calling a child component as a root component. Silly me.
So, please double-check that. Otherwise, it will throw the "useTheme" validation error.
I found out that if you do not put the container tag within a nativebaseprovider tag this will cause that error
EG
/Before declaring the class / const config = { dependencies: { // For Expo projects (Bare or managed workflow) 'linear-gradient': require('expo-linear-gradient').LinearGradient, // For non expo projects // 'linear-gradient': require('react-native-linear-gradient').default, }, };
/In Your Render function/ <NativeBaseProvider config={config}> <Container> / Contents of view here or what you wanna put / </Container> </NativeBaseProvider>
I'm not sure if you have the same solution but this worked for me thanks to @dimtim
I found out that if you do not put the container tag within a nativebaseprovider tag this will cause that error
EG
/Before declaring the class / const config = { dependencies: { // For Expo projects (Bare or managed workflow) 'linear-gradient': require('expo-linear-gradient').LinearGradient, // For non expo projects // 'linear-gradient': require('react-native-linear-gradient').default, }, };
/In Your Render function/
/ Contents of view here or what you wanna put / I'm not sure if you have the same solution but this worked for me thanks to @dimtim
Yes for solve this problem just add component parent NativeBaseProvider in app.js
I found out that if you do not put the container tag within a nativebaseprovider tag this will cause that error
EG
/Before declaring the class / const config = { dependencies: { // For Expo projects (Bare or managed workflow) 'linear-gradient': require('expo-linear-gradient').LinearGradient, // For non expo projects // 'linear-gradient': require('react-native-linear-gradient').default, }, };
/In Your Render function/
/ Contents of view here or what you wanna put / I'm not sure if you have the same solution but this worked for me thanks to @dimtim
I have the same problem and tried to solve it like that, but for that you should install the linear gradient first, or? Do you think there is another solution without installing these?
i got the same error,,
only able to fix by change component as mentioned in official docs https://docs.nativebase.io/radio
export default () => {
return (
<NativeBaseProvider>
<Center flex={1} px="3">
<Example />
</Center>
</NativeBaseProvider>
)
}
this fix is ok only if i learning the example as same as Docs, but this should not be the case to fix the issue i think..
you have to put
nothing here
<NativeBaseProvider>
All here.....
</NativeBaseProvider>
nothing here
If you are working with a main component like App.js and you are using native-base components on all of your app elements, it is a good idea to put the NativeBaseProvider wrapper component at the App.js, if not you can put it on the specific component e.g HomeScreen.js.
I'm getting this error when running jest tests. I've wrapped everything in the <NativeBaseProvider>
tag, still not working.
I managed to solve that error by wrapping the actual component I was testing in <NativeBaseProvider>
const tree = renderer.create(<NativeBaseProvider><ComponentToTest /></NativeBaseProvider>).toJSON()
Same here, add NativeBaseProvider
like @phoenixbeats01 said partially resolve, because seems my snapshoot tree is empty, like if NativeBaseProvider not render childrens
it('renders correctly', () => {
const tree = renderer.create(< NativeBaseProvider><PermissionAction text="HAR!!!!" buttonLabel="IAM A BUTTON" buttonAction={()=>null} /></NativeBaseProvider >).toJSON();
expect(tree).toMatchSnapshot();
});
and my snapshoot
exports[`Permission Action renders correctly 1`] = `
<RNCSafeAreaProvider
onInsetsChange={[Function]}
style={
Array [
Object {
"flex": 1,
},
undefined,
]
}
/>
`;
And yes, my PermissionAction
renders correctly when run on device
I faced the same error on my project. Did someone solve this problem?
I get the same error
useTheme
must be used within NativeBaseConfigProvider Followed docs https://docs.nativebase.io/testing#page-title
Error
console.error
The above error occurred in the<ForwardRef>
component: node_modules/native-base/lib/commonjs/utils/styled.js:45:22 node_modules/native-base/lib/commonjs/components/primitives/Input/InputBase.tsx:111:31 node_modules/native-base/lib/commonjs/components/primitives/Input/Input.tsx:123:10 node_modules/native-base/lib/commonjs/components/composites/Toast/Toast.tsx:240:7
@surajahmed Please review this
@rayan1810 Can you check this please
Any news on this? I simply cannot test anything on my app because of this issue.
Any news on this? I simply cannot test anything on my app because of this issue.
I've solve this... click on link
@dimtim Thanks for the solution.
useTheme
hook (other NativeBase hooks as well) outside NativeBaseProvider.
Our App.js should look like thisimport React from "react";
// 1. import `NativeBaseProvider` component
import { NativeBaseProvider, Text, Box } from "native-base";
function Example () {
const {theme} = useTheme(); // This will work fine as it is inside NativeBaseProvider
return <Box flex={1} bg="#fff" alignItems="center" justifyContent="center">
<Text>Open up App.js to start working on your app!</Text>
</Box>
}
export default function App() {
// 2. Use at the root of your app
// 3. We cannot use useTheme here. This will throw an error.
return (
<NativeBaseProvider>
<Example/>
</NativeBaseProvider>
);
}
Going to close this issue. Please feel free to reopen if you face any problems. Thanks ❤️
I'm still facing the issue regarding the tests...
The app runs fine and everything since I wrapped the App.js content inside the NativeBaseProvider
tag but when running unit tests against React components I get the useTheme must be used within NativeBaseConfigProvider
error. I then wrapped the render of the tested component inside the NativeBaseProvider
in the test file but that just changes the error to something not very understandable.
How did you guys manage to test your code?
Hi,
MrVico @.***> escreveu no dia segunda, 12/09/2022 à(s) 18:04:
I'm still facing the issue regarding the tests...
The app runs fine and everything since I wrapped the App.js content inside the NativeBaseProvider tag but when running unit tests against React components I get the useTheme must be used within NativeBaseConfigProvider error. I then wrapped the render of the tested component inside the NativeBaseProvider in the test file but that just changes the error to something not very understandable.
How did you guys manage to test your code?
— Reply to this email directly, view it on GitHub https://github.com/GeekyAnts/NativeBase/issues/4303#issuecomment-1244032492, or unsubscribe https://github.com/notifications/unsubscribe-auth/ANC75SCTP7OEC5W4XI5BYFDV55PCBANCNFSM5IBKS66Q . You are receiving this because you commented.Message ID: @.***>
@surajahmed Please, reopen the issue, @MrVico is right there are still errors when you try to write tests.
@dimtim Thanks for the solution.
- NativeBaseProvider should be at the root level of the react tree.
- We cannot use
useTheme
hook (other NativeBase hooks as well) outside NativeBaseProvider. Our App.js should look like thisimport React from "react"; // 1. import `NativeBaseProvider` component import { NativeBaseProvider, Text, Box } from "native-base"; function Example () { const {theme} = useTheme(); // This will work fine as it is inside NativeBaseProvider return <Box flex={1} bg="#fff" alignItems="center" justifyContent="center"> <Text>Open up App.js to start working on your app!</Text> </Box> } export default function App() { // 2. Use at the root of your app // 3. We cannot use useTheme here. This will throw an error. return ( <NativeBaseProvider> <Example/> </NativeBaseProvider> ); }
Going to close this issue. Please feel free to reopen if you face any problems. Thanks ❤️
Gives error when testing: useTheme must be used within NativeBaseConfigProvider
Please re-open!
To fix the testing issue, you can simply pass initialWindowMetrics to NativeBaseProvider in your tests.
const inset = {
frame: { x: 0, y: 0, width: 0, height: 0 },
insets: { top: 0, left: 0, right: 0, bottom: 0 },
};
<NativeBaseProvider initialWindowMetrics={inset}>
{children}
</NativeBaseProvider>
Like others in this thread, I have been countering the following error within my Jest unit tests:
`useTheme` must be used within `NativeBaseConfigProvider`
There's a lot of posts saying to just add a "NativeBaseProvider" which is all that's required in most cases, but depending on the repo setup, this may or may not work.
If you're utilising a pnpm or yarn monorepo that imports native-base
in multiple packages, it's possible that there is more than 1 copy of native-base
installed within the various node_modules folders. This can incorrectly result in different versions of the NativeBaseConfig context being used.
Thankfully, we can force Jest to resolve the same version of native-base
, regardless of where it is being imported by adding the following to jest.config.js
:
const path = require('path');
/** @type {import('jest').Config} */
module.exports = {
...
moduleNameMapper: {
'native-base': path.join(__dirname, '../../node_modules/native-base'),
},
};
For some additional context, I'm utilising a pnpm monorepo with the following structure:
monorepo root
node_modules
native-base <-- hoisted version of the library that's shared by multiple packages/apps
packages
components <-- custom components/molecules
node_modules
native-base <-- a version of the library that's specific to `components`
src
Potato.tsx <-- uses `native-base`
feature-auth
src
LoginForm.tsx <-- utilises `Potato` from local `components` package
LoginForm.test.tsx
It was in my LoginForm.test.tsx
where I encountered the error, specifically within the Potato
component. One might expect that simply adding a NativeBaseProvider
in the LoginForm.test.tsx
would solve the issue, but it didn't. The reason is that a different version of the Context was being loaded.
NativeBaseConfigProvider
from root node_modules folder: '../../../../node_modules/native-base'NativeBaseConfigProvider
from its own node_modules folder: '../node_modules/native-base'Even though they have the same name, they're actually utilising completely different versions of the library. Which explains why the Context.Consumer within useTheme
is unable to find the Context.Provider. By adding the jest config above, we can force the native-base
to be imported from the root node-modules folder in both feature-auth
and components
🎉
One thing I found was that there were two copies of native-base
on my monorepo so you have to ensure that all components resolve to the same version.
This works for me https://docs.nativebase.io/testing#page-title
MyTestfile-test.tsx
import 'react-native';
import React from 'react';
import { Test } from '../screens/Test';
import { render } from '@testing-library/react-native';
import { NativeBaseProvider } from 'native-base';
const inset = {
frame: { x: 0, y: 0, width: 0, height: 0 },
insets: { top: 0, left: 0, right: 0, bottom: 0 },
};
it('renders correctly', () => {
const wrapper = render(
<NativeBaseProvider initialWindowMetrics={inset}>
<Test />
</NativeBaseProvider>,
);
wrapper.findByText('Test');
});
Test.tsx
import { Text } from 'native-base';
import React from 'react';
export const Test = () => {
return <Text testID='test'>Test</Text>;
};
Same here, add
NativeBaseProvider
like @phoenixbeats01 said partially resolve, because seems my snapshoot tree is empty, like if NativeBaseProvider not render childrensit('renders correctly', () => { const tree = renderer.create(< NativeBaseProvider><PermissionAction text="HAR!!!!" buttonLabel="IAM A BUTTON" buttonAction={()=>null} /></NativeBaseProvider >).toJSON(); expect(tree).toMatchSnapshot(); });
and my snapshoot
exports[`Permission Action renders correctly 1`] = ` <RNCSafeAreaProvider onInsetsChange={[Function]} style={ Array [ Object { "flex": 1, }, undefined, ] } /> `;
And yes, my
PermissionAction
renders correctly when run on device
Hi, This answer works for me. You can try it. Here is the link. https://github.com/GeekyAnts/NativeBase/issues/3907#issuecomment-919037353
> Same here, add `NativeBaseProvider` like @phoenixbeats01 said partially resolve, because seems my snapshoot tree is empty, like if NativeBaseProvider not render childrens > ```js > it('renders correctly', () => { > const tree = renderer.create(< NativeBaseProvider> ).toJSON(); > expect(tree).toMatchSnapshot(); > }); > ``` > > > > > > > > > > > > and my snapshoot > ``` > exports[`Permission Action renders correctly 1`] = ` >null} /> onInsetsChange={[Function]} > style={ > Array [ > Object { > "flex": 1, > }, > undefined, > ] > } > /> > `; > ``` > > > > > > > > > > > > And yes, my `PermissionAction` renders correctly when run on device Hi, This answer works for me. You can try it. Here is the link. [#3907 (comment)](https://github.com/GeekyAnts/NativeBase/issues/3907#issuecomment-919037353)
@helloworld-Andrew - Can you please provide a sample example with full code.?
Same error after ugprading to 3.2.2 from 2.15.2. I am using react navigation and not sure where to put NavtiveBaseProvider since react navigation has a root component which is already in App.js.
@emclab - Same problem.Are you fixed this issue?
Same error after ugprading to 3.2.2 from 2.15.2. I am using react navigation and not sure where to put NavtiveBaseProvider since react navigation has a root component which is already in App.js.
@emclab - Same problem.Are you fixed this issue?
Just wrap your React Navigation Provider/Root Component with NativeBaseProvider
Same error after ugprading to 3.2.2 from 2.15.2. I am using react navigation and not sure where to put NavtiveBaseProvider since react navigation has a root component which is already in App.js.
@emclab - Same problem.Are you fixed this issue?
Just wrap your React Navigation Provider/Root Component with NativeBaseProvider
@rayan1810 - I am using react-navigation version 4 in the project.Any suggestions?
Wrap the root of your App with the NativeBaseProvider
.
Wrap the root of your App with the
NativeBaseProvider
.
@rayan1810 - I am using the "native-base": "^2.15.2", in my project has react-native version:0.73.2. I need to update the native-base without NativeBaseProvider.My client does not need the header style. Any suggestion, please.
You can't upgrade NativeBase without NativeBaseProvider
You can't upgrade NativeBase without NativeBaseProvider
Can you please suggest any other version without NativeBaseProvider?
Firebase.json { "name": "myapp", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint ." }, "dependencies": { "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@react-native-community/async-storage": "^1.11.0", "@react-native-community/checkbox": "^0.5.2", "@react-native-community/datetimepicker": "^3.0.2", "@react-native-community/netinfo": "^5.9.5", "@react-native-community/picker": "^1.8.0", "@react-native-community/slider": "^3.0.3", "@react-native-community/toolbar-android": "0.1.0-rc.2", "@react-native-firebase/admob": "^7.6.8", "@react-native-firebase/app": "^8.4.5", "@react-navigation/native": "^6.0.6", "material-design-icons": "^3.0.1", "native-base": "^3.0.0", "nodemailer": "^6.4.14", "patch-package": "^6.4.7", "prop-type": "0.0.1", "react": "16.9.0", "react-native": "^0.66.3", "react-native-calendars": "^1.403.0", "react-native-chart-kit": "^6.6.1", "react-native-color-picker": "^0.6.0", "react-native-device-info": "^5.2.1", "react-native-easy-grid": "^0.2.2", "react-native-elements": "^2.3.2", "react-native-exit-app": "^1.1.0", "react-native-fs": "^2.16.4", "react-native-hr-component": "^2.0.2", "react-native-image-picker": "^2.3.4", "react-native-linear-gradient": "^2.5.6", "react-native-mail": "^5.2.0", "react-native-modal": "^11.5.6", "react-native-modal-datetime-picker": "^9.0.0", "react-native-modal-selector": "^1.1.2", "react-native-month-selector": "^1.4.0", "react-native-month-year-picker": "^1.4.1", "react-native-orientation": "^3.1.3", "react-native-paper": "^3.12.0", "react-native-permissions": "^2.2.2", "react-native-restart": "^0.0.17", "react-native-safe-area-context": "^3.3.2", "react-native-screens": "^2.9.0", "react-native-simple-toast": "^1.0.0", "react-native-svg": "^9.12.0", "react-native-video": "^5.1.0-alpha8", "react-native-video-controls": "^2.6.0", "react-native-video-player": "^0.10.1", "react-native-webview": "^11.14.2", "rn-fetch-blob": "^0.12.0" }, "devDependencies": { "@babel/core": "^7.6.2", "@babel/runtime": "^7.6.2", "@react-native-community/eslint-config": "^3.0.1", "babel-jest": "^27.3.1", "eslint": "^8.2.0", "jest": "^27.3.1", "metro": "^0.66.2", "metro-react-native-babel-preset": "^0.56.0", "moment": "^2.24.0", "react-native-gesture-handler": "^1.4.1", "react-native-reanimated": "^1.2.0", "react-native-render-html": "^4.1.2", "react-native-sqlite-storage": "^4.1.0", "react-native-vector-icons": "^7.1.0", "react-navigation": "^4.4.4", "react-navigation-drawer": "^2.2.2", "react-navigation-stack": "^1.8.1", "react-test-renderer": "16.9.0" }, "jest": { "preset": "react-native" } }
This error is located at: in Container in HomeScreen (created by SceneView) in SceneView (at StackViewLayout.tsx:900) in RCTView (at View.js:32) in Unknown (at createAnimatedComponent.js:242) in AnimatedComponent (at createAnimatedComponent.js:295) in AnimatedComponentWrapper (at StackViewCard.tsx:106) in RCTView (at View.js:32) in Unknown (at createAnimatedComponent.js:242) in AnimatedComponent (at createAnimatedComponent.js:295) in AnimatedComponentWrapper (at src/index.native.js:105) in Screen (at StackViewCard.tsx:93) in Card (at createPointerEventsContainer.tsx:95) in Container (at StackViewLayout.tsx:975) in RCTView (at View.js:32) in Unknown (at src/index.native.js:139) in ScreenContainer (at StackViewLayout.tsx:384) in RCTView (at View.js:32) in Unknown (at createAnimatedComponent.js:242) in AnimatedComponent (at createAnimatedComponent.js:295) in AnimatedComponentWrapper (at StackViewLayout.tsx:374) in PanGestureHandler (at StackViewLayout.tsx:367) in StackViewLayout (created by withOrientation) in withOrientation (at StackView.tsx:104) in RCTView (at View.js:32) in Unknown (at Transitioner.tsx:267) in Transitioner (at StackView.tsx:41) in StackView (created by Navigator) in Navigator (created by KeyboardAwareNavigator) in KeyboardAwareNavigator (created by SceneView) in SceneView (created by Drawer) in RCTView (at View.js:32) in Unknown (created by ResourceSavingScene) in RCTView (at View.js:32) in Unknown (created by ResourceSavingScene) in ResourceSavingScene (created by Drawer) in RCTView (at View.js:32) in Unknown (at src/index.native.js:139) in ScreenContainer (created by Drawer) in RCTView (at View.js:32) in Unknown (at createAnimatedComponent.js:240) in AnimatedComponent(View) (created by Drawer) in RCTView (at View.js:32) in Unknown (at createAnimatedComponent.js:240) in AnimatedComponent(View) (created by PanGestureHandler) in PanGestureHandler (created by Drawer) in Drawer (created by DrawerView) in DrawerView (created by Navigator) in Navigator (created by NavigationContainer) in NavigationContainer (at myapp/index.js:24) in ThemeProvider (created by Provider) in RCTView (at View.js:32) in Unknown (created by Portal.Host) in Portal.Host (created by Provider) in Provider (at myapp/index.js:23) in Main (at renderApplication.js:50) in RCTView (at View.js:32) in Unknown (at AppContainer.js:92) in RCTView (at View.js:32) in Unknown (at AppContainer.js:119) in AppContainer (at renderApplication.js:43) in myapp(RootComponent) (at renderApplication.js:60) ERROR Error:
useTheme
must be used withinNativeBaseConfigProvider
This error is located at: in NavigationContainer (at myapp/index.js:24) in ThemeProvider (created by Provider) in RCTView (at View.js:32) in Unknown (created by Portal.Host) in Portal.Host (created by Provider) in Provider (at myapp/index.js:23) in Main (at renderApplication.js:50) in RCTView (at View.js:32) in Unknown (at AppContainer.js:92) in RCTView (at View.js:32) in Unknown (at AppContainer.js:119) in AppContainer (at renderApplication.js:43) in myapp(RootComponent) (at renderApplication.js:60) ERROR Error:
useTheme
must be used withinNativeBaseConfigProvider
This error is located at: in NavigationContainer (at myapp/index.js:24) in ThemeProvider (created by Provider) in RCTView (at View.js:32) in Unknown (created by Portal.Host) in Portal.Host (created by Provider) in Provider (at myapp/index.js:23) in Main (at renderApplication.js:50) in RCTView (at View.js:32) in Unknown (at AppContainer.js:92) in RCTView (at View.js:32) in Unknown (at AppContainer.js:119) in AppContainer (at renderApplication.js:43) in myapp(RootComponent) (at renderApplication.js:60)
HomeScreen.Java
import React, { Component } from 'react'; import { StyleSheet, View, Text, Image, TouchableOpacity, Linking,ScrollView, TouchableWithoutFeedback, Keyboard, Dimensions, Platform, Clipboard } from 'react-native'; import { TextInput, Snackbar } from 'react-native-paper'; import Toast from 'react-native-simple-toast'; import style from '../styles/CommonLayout'; import GLOBALS from '../customlibs/Globals'; import { DatabaseHelper } from '../customlibs/DatabaseHelper'; import AsyncStorage from '@react-native-community/async-storage'; import { UtilityHelper } from '../customlibs/UtilityHelper'; import LinearGradient from 'react-native-linear-gradient'; var RNFS = require('react-native-fs'); import { Container, Header, Content,Button, Icon, Footer } from 'native-base'; import { Col, Row, Grid } from 'react-native-easy-grid'; import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'; import { Tips } from '../model/Tips'; import Moment from 'moment'; import { BannerAd, BannerAdSize, TestIds } from '@react-native-firebase/admob'; import DeviceInfo from 'react-native-device-info'; import AdBanner from '../layoutelements/AdBanner' import Modal from 'react-native-modal';
const pageStyles = StyleSheet.create({ mainContainer: { flex: 1, marginTop: 5, marginLeft: 15, marginRight: 15, marginBottom: 15 }, modalContent: { backgroundColor: 'white', padding: 5, justifyContent: 'center', borderWidth:4, borderColor: '#000000', borderRadius: 10 }, });
export default class HomeScreen extends Component { constructor(props) { super(props) this.state = { background_color: '#5c5c5c', password: '', tip_today: 0, ads_path: require('../images/banner1.png'), newUpdateSnackbar: false, announcementModalVisible: false, announcements: null }; this.utilHelper = new UtilityHelper(); this.dbHelper = new DatabaseHelper(); this.tipsModel = new Tips(); this.willFocusSubscription; }
componentDidMount(){
}
componentWillUnmount(){ this.willFocusSubscription.remove()
}
pokeservercount(id) { try { AsyncStorage.multiGet(['user_data','background_color'], (err, items) => { if(items[0][1] != '' && items[0][1] != 'undefined' && items[0][1] != null){ var myObject = JSON.parse(items[0][1]); fetch("http://webcoastserver.com/central/public.php",{ method: 'POST', headers: new Headers({ 'Content-type' : 'application/x-www-form-urlencoded', }), body: "action=updateviews&aid="+id+"&uid="+myObject.user_id }).then((response)=>{
}
convertTimeFromStampToDisplay(timestamp, monthname = true) { return Moment(timestamp, "YYYY-MM-DD HH:mm").format((monthname ? "MMM DD YYYY hh:mm A" : "MM DD YYYY hh:mm A")); }
async loadData() { AsyncStorage.multiGet(['background_color'], (err, items) => { //console.log(items[0][1]) if(items[0][1] != 'undefined' && items[0][1] != null){ this.setState({ background_color: items[0][1] }); } }); var formatdate_sql = Moment(new Date()).format('YYYY/MM/DD'); this.tipsModel.getTipsByQuery("SELECT * FROM "+GLOBALS.TIPS+" where tipdate='"+formatdate_sql+"'") .then((result) => { if(result.length > 0){ this.setState({ tip_today: result[0].tipamt }) } },(err) => {})
}
async checkVersion() { fetch("###########", { method: 'GET', headers: new Headers({ 'Content-Type': 'application/json', // <-- Specifying the Content-Type }) }) .then(response => response.json() ) .then(data => { //console.log(data.android_version) if(Platform.OS == 'ios') {
}
render() { const { checked } = this.state; const {navigate} = this.props.navigation;
} }
Actions to duplicate: npm install pod install run in ios