Error: Invariant Violation: The element type provided is not valid in React Native

I embarked on my journey to learn React Native just 4-5 days ago, and already I am diving into creating a login screen in React Native. However, I have hit a roadblock and despite my efforts, I am unable to resolve the issue. Could you please lend me your expertise? You can view the code and error screenshot here.

App.js
import React, { Component} from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Login from './src/screens/Login';


export default class App extends Component {
  render() {
    return (
       <Login />
    );
  }
}

Here is the Login screen code

Login.js


  import React, { Component} from 'react';
import { StyleSheet, TextInput, View, Image, StatusBar, Dimensions } from 'react-native';
import { LinearGradient } from 'expo';
import EStyleSheet from 'react-native-extended-stylesheet';
import { Button }  from '../components/Button';
import { Ionicons } from '@expo/vector-icons';

const {width: WIDTH} = Dimensions.get('window')

EStyleSheet.build();

export default class Login extends Component {
  render() {
    return (
      <LinearGradient
      colors={['#38E870', '#2BB256']} 
      style={styles.container}>
      <StatusBar barStyle="light-content" />
      <View style={styles.logocontainer}>
        <Image source={require('../images/Devastic.png/')} />
      </View>
      <View style={styles.formContainer}>
      <View style={styles.inputcontainer}>
      <Ionicons name="ios-person-outline" size={36} color="#747475" 
      style={styles.inputemail}/>
           <TextInput 
           placeholder={'Enter Your Email'}
           underlineColorAndroid={'transparent'}
           placeholderTextColor="#dfe6e9"
           style={styles.input}
           />
           <Ionicons name="ios-unlock-outline" size={34} color="#747475" 
      style={styles.inputpass}/>
           <TextInput 
           placeholder={'Enter Your Password'}
           secureTextEntry={true}
           underlineColorAndroid={'transparent'}
           placeholderTextColor="#dfe6e9"
           style={styles.input}
           />     
           <Button
           text="Log In"
           onPress={() => console.log ("Pressed")}
            />
            </View>
      </View>
      </LinearGradient>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    },
    logocontainer: {
        paddingTop: 50,
    },
    formContainer: {
      backgroundColor: '#FFF',
      marginTop: 180,
      width: 360,
      height: 340,
      borderRadius: 10,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.6,
      shadowRadius: 6,
      elevation: 8,
      },
      inputcontainer: {
        marginTop: 30,
      },
      inputemail: {
               position: 'absolute',
               left: 18,
               top: 13,
      },
      inputpass: {
        position: 'absolute',
               left: 18,
               top: 77,
      },

      input: {
      width: WIDTH -50 ,
      height: 44,
      padding: 10,
      paddingLeft: 40,
      marginVertical: 10,
      marginHorizontal: 10,
      borderWidth: 1,
      borderRadius: 20,
      borderColor: 'black',
      marginBottom: 10,
      }
});

Here is the Button.js File code

import React from 'react';
    import { View, TouchableHighlight, TouchableNativeFeedback, Text, Platform } from 'react-native';
    import EStyleSheet from 'react-native-extended-stylesheet';

    const styles = EStyleSheet.create({
      $buttonColor: '#38E870',
      $buttonTextColor: '#ffffff',
      $buttonUnderlayColor: '#2BB256',
      button: {
        backgroundColor: '$buttonColor',
        paddingVertical: 10,
        paddingHorizontal: 30,
        marginHorizontal: 12,
        borderRadius: 40,
        marginTop: 20,
        },
      text: {
        color: '$buttonTextColor',
        fontSize: 18,
        textAlign: 'center',
        fontWeight: 'bold',
      },
    });

    export const Button = ({ text, onPress }) => {
      if (Platform.OS === 'ios') {
        return (
          <TouchableHighlight
            onPress={onPress}
            style={styles.button}
            underlayColor={styles.$buttonUnderlayColor}
          >
            <Text style={styles.text}>{text}</Text>
          </TouchableHighlight>
        );
      }

      return (

        <TouchableNativeFeedback
          onPress={onPress}
          background={TouchableNativeFeedback.Ripple(styles.$buttonUnderlayColor)}
        >
          <View style={styles.button}>
            <Text style={styles.text}>{text}</Text>
          </View>
        </TouchableNativeFeedback>
      );
    };

Answer №1

Within your Login.js file, you are currently importing Button as an object.

Make the following adjustment:

Replace

import { Button }  from '../components/Button';

With

import Button from '../components/Button';

If you need more details, please refer to: Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I hope this resolves your issue!

Answer №2

The issue seems to stem from how you have exported the Button component.

export foo;
import {foo} from 'blah';

export default foo;
import foo from 'blah';

To solve your problem, try replacing this:

export const Button = ({ text, onPress }) => 

with the following:

export default const Button = ({ text, onPress }) => 

For more information, you can refer to this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging JavaScript for pricing calculations within asp.net framework

I am currently working with a textbox in a gridview and trying to calculate values using JavaScript. My code seems to be error-free. The goal is to multiply the quantity by the rate to get the total price. function totalise(price, rate, qt) { var qt ...

Promise disregards the window being open

I'm facing an issue with redirecting users to Twitter using window.open in a specific function. It seems like the instruction is being ignored, even though it works perfectly on other pages. Any ideas on how to fix this? answerQuestion() { if ...

Choosing an item from a dropdown menu that is not built with the Select function in Puppeteer

In our project, we have implemented a drop down feature using React AntD design which does not utilize the Select tag. You can find an example of this implementation here. https://i.sstatic.net/pRG1m.png The options for the drop down are generated using ...

Is there a way to adjust the quantity of items in the shopping cart without the need to reload the webpage?

Currently, I am working on a test project using React & Redux. The project involves implementing a basket feature where I receive an array of products structured like this: products: [ { name: "Product one", count: 1, ...

Unpacking a mongoose record

During my project using mongoose, I encountered a issue. I am trying to retrieve all documents that contain a specific key and value pair role: USER. Although I am able to retrieve a list of documents, I am struggling to access the values of certain fields ...

Is it better to bind a function to each object individually or create a helper object in Javascript/AngularJS?

Here's a quick question that I'm not sure how to search for online. Imagine you have a JSON list of 'persons' from an API in AngularJS, and you convert it into a JavaScript array/object: [ {firstName: 'Foo', lastName: &apo ...

Issues arise when node error handlers encounter bugs while utilizing the error pattern (err, req, res, next)

Currently, my node application is running with the express middleware for handling requests using the GET method. I have implemented error handling for 404s or 500s at the end of my script, after the GET method. However, I have encountered an issue with us ...

Reliable Image Visualization with JavaScript

I am encountering an issue with my code, where it successfully displays a preview of the uploaded image in Firefox using the following script: var img = document.createElement('img'); img.src = $('#imageUploader').get(0).files[0].getAs ...

Is web analytics done via client-side (JavaScript) or server-side logging on websites?

As I embark on creating a web application to track web statistics for my clients, I've run into a dilemma. With the rise of ajax usage, I'm unsure whether it's best to log a user visit using JavaScript or serverside. Additionally, I'm u ...

Saving two separate arrays in local storage using JavaScript

Let's say I have two arrays: myFavCars and myDislikedCars. How can I combine them and store in local storage like this: localStorage.setItem('myPreferences', { myFavCars: [], myDislikedCars: [] }) Is it feasible to store two separate arrays ...

Creating a secure authentication system with Parse for password recovery and website logins

Our organization has chosen to utilize a Parse backend for managing user accounts, and I am tasked with creating web pages for functionalities like password reset that will seamlessly integrate with our mobile applications. It has been some time since I ha ...

What steps are necessary to create an npm package utilizing three.js without any dependencies?

I have a challenge - I am trying to create an npm package that generates procedural objects for three.js. The issue I'm facing is how to properly include three.js in my code. I attempted to establish a dependency and use something like const THREE = r ...

Exploring React-Redux: The Origin of Children Components

Currently, I'm following a tutorial on react-redux which can be found at the following URL: http://redux.js.org/docs/basics/ExampleTodoList.html As I analyze the code in link.js, I'm curious about the source of the {children} element. import R ...

Utilizing the Power of Magicline in Conjunction with Flexslider

Currently, I am implementing Flexslider for a slideshow on my website and I am attempting to integrate Magicline with it. The functionality is working well, but I have encountered an issue where the magicline does not move when clicking on the navigation a ...

OneSignal for Android - function necessitates a restful API key

Greetings to all! I am in the process of creating an Android app that utilizes OneSignal. I have come across a hurdle where I am unsure how to provide the server with the necessary REST API key. Any assistance would be greatly appreciated. Thank you! ...

Making AJAX requests with Laravel using the XMLHttpRequest object is a

When using Laravel to upload a file and create a progress bar with ajax requests, the form action routes to the controller in this way: <form action="{{ URL::route('upload-file-form-post') }}" method="POST" enctype="multipart/form-data"> ...

The initial page load is experiencing issues with input type validations not functioning properly

I'm facing an issue with my text box where I only want to allow alphabets to be entered. Here is my code snippet: state ={ NomName: '', } onlyAlpha(e) { var regex = /^[a-zA-Z ]*$/; if(e.target.value === '' || regex.t ...

Utilize JavaScript to implement CSS using an "if" statement

I am currently working on implementing iOS web app properties into my website. My goal is to create a <div> at the top of the page and apply specific CSS styles when a certain condition is met in a JavaScript script. Unfortunately, I am facing issue ...

Encountering issues with DatePickerDialog functionality within a fragment

Encountering an issue when trying to add the DataPickerDialog to my project, which follows the drawer layout example of Android Studio. package asaek.ikusi.ikusi_1.ui.home import android.app.DatePickerDialog import android.os.Bundle import android.view.La ...

What is the best way to set a date input as required with AngularJS?

Angular 1.2.23 is the version I am currently using, and I want to set an input field with type=date as required. Here is the code snippet I have: <form name="form" novalidate> <input id="date" name="date" type="date" required /> <sp ...