Expo react native Element type is invalid: expected a string or a class/function but got: undefined - javascript

I try to learn react-native sorry if this is a dump question.
I created an demo app with expo init using managed flow. And try to add carousel in home screen by using react-native-sideswipe.
I found an example snack and tried to add it in my app. But I am getting this error for Carousel component in HomeScreen.js :
Invariant Violation: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I can't figure out what is the problem and how can I solve this. I check the components and props are exists in the version which I am using.
Related part of App.js:
const [isLoadingComplete, setLoadingComplete] = useState(false);
if (!isLoadingComplete && !props.skipLoadingScreen) {
return (
<AppLoading
startAsync={loadResourcesAsync}
onError={handleLoadingError}
onFinish={() => handleFinishLoading(setLoadingComplete)}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
);
}
}
Related part of AppNavigator.js
import React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import MainTabNavigator from './MainTabNavigator';
export default createAppContainer(
createSwitchNavigator({
// You could add another route here for authentication.
// Read more at https://reactnavigation.org/docs/en/auth-flow.html
Main: MainTabNavigator,
})
);
Related part of MainTabNavigator.js
import React from 'react';
import { Platform } from 'react-native';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import HomeScreen from '../screens/HomeScreen';
const config = Platform.select({
web: { headerMode: 'screen' },
default: {},
});
const HomeStack = createStackNavigator(
{
Home: HomeScreen,
},
config
);
HomesSreen.js:
import React from 'react';
import {
Animated,
Easing,
Image,
Platform,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
Dimensions,
} from 'react-native';
import { Constants } from 'expo';
import { MonoText } from '../components/StyledText';
import { Carousel, AnimatedCarouselItem } from 'react-native-sideswipe';
import { Card, Badge } from 'react-native-elements';
const { width } = Dimensions.get('window');
const data = [1, 2, 3, 4, 5];
export default function HomeScreen() {
return (
<View style={styles.container}>
<ScrollView
style={styles.container}
contentContainerStyle={styles.contentContainer}>
<View style={styles.welcomeContainer}>
<Image
source={require('../assets/images/logo.png')}
style={styles.headerImage}
/>
<Carousel
data={data}
style={{ width, maxHeight: 225 }}
itemWidth={width}
threshold={120}
contentOffset={0}
renderItem={({ item }) => (
<View style={{ width: width, paddingHorizontal: 10 }}>
<Card
title="Local Modules"
containerStyle={{ maxWidth: width, height: 225 }}>
<Badge value={item} />
<Text style={{ marginTop: 10 }}>
Science
</Text>
</Card>
</View>
)}
/>
</View>
<View style={styles.helpContainer}>
</View>
</ScrollView>
<View style={styles.tabBarInfoContainer}>
</View>
</View>
);
}
Thanks for your help!

I think you need to export HomeStack from MainTabNavigator.js:
export default const HomeStack = createStackNavigator({
Home: HomeScreen,
},
config
);
Let me know if that doesn't work.

Related

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Imports

I can't get rid of this error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
This is ProductContainer.js
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, ActivityIndicator, FlatList } from 'react-native';
import { Container, Header, Item, Icon, Input, Text } from 'native-base';
import ProductList from './ProductList';
const data = require('../../assets/data/products.json');
const ProductContainer = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
setProducts(data);
return () => {
setProducts([]);
};
}, []);
return (
<Container>
<Header searchBar rounded>
<Item>
<Icon name="ios-search" />
<Input placeholder="Search" />
</Item>
</Header>
<View>
<Text>Product Container</Text>
<View style={{ marginTop: 100 }}>
<FlatList
data={products}
numColumns={2}
renderItem={({ item }) => <ProductList key={item.id} item={item} />}
keyExtractor={(item) => item.name}
/>
</View>
</View>
</Container>
);
};
export default ProductContainer;
and this is my App.js:
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { NativeBaseProvider } from 'native-base';
//Screens
import Header from './Shared/Header';
import ProductContainer from './screens/Products/ProductContainer';
export default function App() {
return (
<NativeBaseProvider>
<View style={styles.container}>
<Header />
<ProductContainer />
</View>
</NativeBaseProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Been stuck on this for days now, please help.
I tried checking my imports and exports but can't figure out where this error is rising from. I also tried putting ProductList in curly braces where I import it in ProductContainer.js but didn't work. I appreciate the help!
Have you tried to enclose your ProductList component in parenthesis and then run your project?
Like this:
import { ProductList} from './ProductList';

Navigate Between Screen React Native

I'm coming from ReactJS and a bit confused about how to navigate between screens in react native.
I'm using these react-navigation and react-navigation-stack versions:
"#react-navigation/native": "^5.8.10", "#react-navigation/stack": "^5.12.8"
So I have 2 screens already:
SplashScreenContainer
import React from 'react';
import {Text, View} from "react-native-reanimated";
class SplashScreenContainer extends React.PureComponent {
redirectToHome = () => {
const {navigation} = this.props;
navigation.navigate('HomeContainer');
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text onPress={() => this.redirectToHome}>
Splash Screen
</Text>
</View>
)
}
}
export default SplashScreenContainer;
HomeScreenContainer
import React from 'react';
import {Text, View} from "react-native-reanimated";
class HomeScreenContainer extends React.PureComponent {
render() {
return (
<View>
<Text>Home Screen</Text>
</View>
)
}
}
export default HomeScreenContainer;
and here's my app js to render the screens inside NavigationContainer:
App.js
import React from 'react';
import {SafeAreaView} from "react-native-safe-area-context";
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
const SplashScreenContainer = React.lazy(() => import('./app/containers/SplashScreenContainer'));
const HomeContainer = React.lazy(() => import('./app/containers/HomeContainer'));
const Stack = createStackNavigator();
class App extends React.PureComponent {
render() {
return (
<SafeAreaView>
<NavigationContainer>
<Stack.Navigatior>
<Stack.Screen name='SplashScreenContainer' component={() => <SplashScreenContainer {...this.props} />}/>
<Stack.Screen name='HomeContainer' component={() => <HomeContainer {...this.props} />}/>
</Stack.Navigatior>
</NavigationContainer>
</SafeAreaView>
)
}
}
export default App;
After I run with npm run ios command, the console gives me this error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I don't understand what is this error about, what am I missing here? how can I navigate between the screens in react-native?
Any help will be much appreciated.
Thank You.
Regards
Well, I made it works. Here are the changes I made:
Remove SafeAreaView from App.js
Add {Suspense} in App.js because I forgot that React.lazy depends on Suspense
Use SafeAreaView in Home and SplashScreen imported from 'react-native'
App.js
import React, {Suspense} from 'react';
import {SafeAreaView, Text} from 'react-native';
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
const SplashScreenContainer = React.lazy(() => import('./app/containers/SplashScreenContainer'));
const HomeContainer = React.lazy(() => import('./app/containers/HomeContainer'));
const Stack = createStackNavigator();
const Loading = () => {
return (
<SafeAreaView>
<Text>Loading</Text>
</SafeAreaView>
)
};
const Routes = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='SplashScreenContainer'>
<Stack.Screen
name='SplashScreenContainer'
component={SplashScreenContainer}
options={{ headerShown: false }}
/>
<Stack.Screen
name='HomeContainer'
component={HomeContainer}
options={{ headerShown: false }}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
class App extends React.PureComponent {
render() {
return (
<Suspense fallback={<Loading/>}>
<Routes/>
</Suspense>
)
}
}
export default App;
SplashScreenContainer.js
import React from 'react';
import {Button, SafeAreaView} from 'react-native';
class SplashScreenContainer extends React.PureComponent {
constructor(props) {
super(props);
}
redirectToHome = () => {
const {navigation} = this.props;
navigation.navigate('HomeContainer');
};
render() {
return (
<SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button onPress={() => this.redirectToHome()} title='Go To Home Screen'/>
</SafeAreaView>
)
}
}
export default SplashScreenContainer;
HomeScreenContainer.js
import React from 'react';
import {Button, SafeAreaView} from 'react-native';
class HomeContainer extends React.PureComponent {
redirectToSplash = () => {
const {navigation} = this.props;
navigation.navigate('SplashScreenContainer');
};
render() {
return (
<SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button onPress={() => this.redirectToSplash()} title='Go To Splash Screen'/>
</SafeAreaView>
)
}
}
export default HomeContainer;
Everything's working now, I'm able to switch between SplashScreen and HomeScreen when button is clicked/tapped.

React Native - Invariant Violation: Element type is invalid: expected string but got: undefiend

So when I use this code everything works just fine:
import * as React from 'react';
import { Button, Image, View, TouchableOpacity, StyleSheet, TouchableWithoutFeedback, KeyboardAvoidingView, SimpleAnimation, Text, TextInput} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';
import { Ionicons } from '#expo/vector-icons';
import FlatButton from './button';
const thirdColor = 'red';
const secColor = 'blue';
const mainColor = 'green';
export default class ImagePickerExample extends React.Component {
state = {
image: null,
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Pick an image from camera roll"
onPress={this._pickImage}
/>
{image &&
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
</View>
);
...
After that, everything I change is inside my redner() method and the code looks so:
...
export default class ImagePickerExample extends React.Component {
state = {
image: null,
};
render() {
let { image } = this.state;
return (
<TouchableWithoutFeedback onPress={() => {
//whenever touched the soroundings, keyboard will be dismissed
Keyboard.dismiss();
}}>
<View style={styles.container}>
<KeyboardAvoidingView behavior='position'>
<SimpleAnimation delay={500} duration={1200} fade staticType='bounce'>
<Text style={{color: thirdColor, fontSize: 61}}>Welcome back</Text>
</SimpleAnimation>
{image &&
<TouchableOpacity onPress={this._pickImage}>
<Ionicons name="ios-person" size={100} color={thirdColor} ></Ionicons>
</TouchableOpacity>}
<SimpleAnimation delay={600} duration={1200} fade staticType='bounce'>
<View style={styles.contYourName}>
<TextInput placeholder='Username' style = {styles.yourName}></TextInput>
</View>
</SimpleAnimation>
<SimpleAnimation delay={900} duration={1200} fade staticType='bounce'>
<View style={styles.regButtonView}>
<FlatButton text='finsih' onPress={alert}/>
</View>
</SimpleAnimation>
</KeyboardAvoidingView>
</View>
</TouchableWithoutFeedback>
);
}
...
After I did this I get following error message on my iPhone through Expo:
error code from IOS
What is wrong with it? My current React Native version is:
react-native-cli: 2.0.1
react-native: 0.61.4
EDIT:
Here are the functions:
componentDidMount() {
this.getPermissionAsync();
console.log('hi');
}
getPermissionAsync = async () => {
if (Constants.platform.ios) {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
}
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1
});
console.log(result);
if (!result.cancelled) {
this.setState({ image: result.uri });
}
};
Another EDIT:
As soon as I comment all <SimpleAnimation></SimpleAnimation> than everything works again. Why is <SimpleAnimation></SimpleAnimation> a problem?
change image state to "" (empty String) instead of null or handle null condition of image uri;
import * as React from 'react';
import { Button, Image, View, TouchableOpacity, StyleSheet, TouchableWithoutFeedback, KeyboardAvoidingView, SimpleAnimation, Text, TextInput} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';
import { Ionicons } from '#expo/vector-icons';
import FlatButton from './button';
const thirdColor = 'red';
const secColor = 'blue';
const mainColor = 'green';
export default class ImagePickerExample extends React.Component {
state = {
image: "",
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Pick an image from camera roll"
onPress={this._pickImage}
/>
{image &&
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
</View>
);
Check all methods are imported which you have used.
use this.state.image instead of image.
Rerun or reload
So the problem was the <SimpleAnimation></SimpleAnimation> tags in my render(). Thats because somehow this import got messed up. So I did the following that fixed my problem:
npm uninstall react-native-simple-animations
npm install react-native-simple-animations
After that import in your code with: import { SimpleAnimation } from 'react-native- simple-animations'; dont forget the { }

Is there a way to make a homescreen for an app instead of App.js, with React Native Navigation?

I am a beginner to React Native and have encountered a problem with navigation. I want my App.js screen to be used for navigation, but I want another file to be the home screen. Is there any way to do this?
This is my App.js code:
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import {HomeScreen} from './components/HomeScreen';
const MainNavigator = createStackNavigator({
Home: {screen: HomeScreen},
Login: {screen: LoginScreen},
});
const App = createAppContainer(MainNavigator);
export default App;
And this is the code of the page I want to make my home screen:
import React from 'react';
import {SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Image, TouchableOpacity} from 'react-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
class HomeScreen extends Component {
render() {
const {navigate} = this.props.navigation;
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Image style={styles.logo} source={require('./components/images/img1.jpg')} />
<Image style={styles.logo} source={require('./components/images/img2.jpg')} />
<Image style={styles.logo} source={require('./components/images/img3.jpg')} />
<Image style={styles.logo} source={require('./components/images/img4.jpg')} />
<Image style={styles.logo} source={require('./components/images/img7.jpg')} />
<Image style={styles.logo} source={require('./components/images/img8.jpg')} />
</ScrollView>
</SafeAreaView>
</>
);
};
}
Thanks.
To make any screen initial you should set it as initialRouteName option like:
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Login: LoginScreen,
}, {
initialRouteName: "Home"
}
);
To be able to import HomeScreen (or any other) from another file you need to export it from that file first. That part is missing from your example.
import * as React from 'react';
import { Button, View, Text } from 'react-native';
export default class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
Here is full snack example for your case, it is extended from react-navigation basic example, do check their documentation.

React Native: React-Navigation Cannot read property 'navigate' of undefined

I am currently learning React Native and was having some issue with React-navigation.
What I am trying to do is switch screen when the "button" is being pressed.
In the "button", I have:
onPress={() =>
navigate('Home')}
I have const { navigate } = this.props.navigation; before the return statement.
When I run it, I am getting "Cannot read property 'navigate' of undefined.
I guess it is I have to place this.props.navigation somewhere.
Here are my two files:
"IntroPageFive" is the one that has the button and "react-navigation".
I would like to go to "IntroPageOne" when the button is being clicked.
Code for "IntroPageFive":
import React from 'react';
import { Text, View, Image, Linking, Button, TouchableOpacity } from 'react-native';
import PlaceholderImage from '../images/placeholder_thumbnail.png';
import SignInFooter from './signInFooter';
import { createStackNavigator } from 'react-navigation';
import IntroPageOne from './introPageOne';
const App = createStackNavigator({
Home: { screen: IntroPageOne },
});
class IntroPageFive extends React.Component {
render() {
const {
headerTextStyle,
thumbnailStyle,
viewStyle,
subTextStyle,
mainTextSection,
footerSectionStyle,
startButtonStyle,
startButtonTextStyle,
signInButtonStyle ,
signInButtonTextStyle
} = styles;
const { navigate } = this.props.navigation;
return (
<View style={viewStyle}>
<Image style={thumbnailStyle} source={require('../images/placeholder_thumbnail.png')} />
<View style={mainTextSection}>
<Text style={headerTextStyle}>Take A Ride For</Text>
<Text style={headerTextStyle}>Your Favorite Car!</Text>
</View>
<View>
<TouchableOpacity
onPress={() =>
navigate('Home')
}
style={startButtonStyle}
>
<Text style={startButtonTextStyle}>LET'S GET STARTED</Text>
</TouchableOpacity>
</View>
<View style={footerSectionStyle}>
<SignInFooter />
</View>
</View>
);
}
}
export default IntroPageFive;
Here is the code for "IntroPageOne":
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import PlaceholderImage from '../images/placeholder_thumbnail.png';
import SignInFooter from './signInFooter';
const IntroPageOne = () => {
const { headerTextStyle, thumbnailStyle, viewStyle, subTextStyle } = styles;
return (
<View style={viewStyle} >
<Image style={thumbnailStyle} source={require('../images/placeholder_thumbnail.png')} />
<Text style={headerTextStyle}>Forget Everything You</Text>
<Text style={headerTextStyle}>Know About Making</Text>
<Text style={headerTextStyle}>Deals For Your Car</Text>
<Text style={subTextStyle}>Deal negotiation powered by AI</Text>
<SignInFooter />
</View>
);
};
};
export default IntroPageOne;
Could anyone please tell me how to fix this issue?
Thank you.

Categories