Home > Back-end >  Error "Element type is invalid" React Native
Error "Element type is invalid" React Native

Time:07-07

Running this react native code gives me the error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

    import React from 'react';
import {Text, Button, View, ScrollView} from 'react';

let id = 0

const Todo = props => (
  <View>
    <Button onPress={props.onDelete} title="delete"/>
    <Text>{props.todo.text}</Text>
  </View>
)

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {
      todos: [],
    }
  }

  addTodo() {
    id  
    const text = `TODO Number ${id}`
    this.setState({
      todos: [
        ...this.state.todos,
        {id: id  , text: text, checked: false},
      ], 
    })
  }

  removeTodo(id) {
    this.setState({
      todos: this.state.todos.filter(todo => todo.id !== id)
    })
  }

  toggleTodo(id) {
    this.setState({
      todos: this.state.todos.map(todo => {
        if (todo.id !== id) return todo
        return {
          id: todo.id,
          text: todo.text,
          checked: !todo.checked,
        }
      })
    })
  }

  render() {
    return (
      <View>
        <Text>Todo count: {this.state.todos.length}</Text>
        <Text>Unchecked todo count: {this.state.todos.filter(todo => !todo.checked).length}</Text>
        <Button onPress={() => this.addTodo()}title="Add TODO"/>
        <ScrollView>
          {this.state.todos.map(todo => (
            <Todo
              onToggle={() => this.toggleTodo(todo.id)}
              onDelete={() => this.removeTodo(todo.id)}
              todo={todo}
            />
          ))}
        </ScrollView>
      </View>
    )
  }
}

when I run this I get the error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. I think is because the export default what do you think?

CodePudding user response:

The issue arises from your 2nd line of code. You're importing your components from react, but you should be importing them from react-native. Replace

import {Text, Button, View, ScrollView} from 'react';

with

import {Text, Button, View, ScrollView} from 'react-native';
  • Related