Home > database >  Yet another "Objects are not valid as a React child " in React Native
Yet another "Objects are not valid as a React child " in React Native

Time:06-17

I am new in React Native but i have been working a bit with React before. I 've got a comparable piece of code working in react some time ago, but now in react-native I keep on receiving this error message.

The code is simplified as much as possible.

Why am I getting this error? No async, i refer to object. etc... in this example.

My code in app.js:

import React, { Component } from 'react';
import { View, StyleSheet, SafeAreaView,ScrollView} from 'react-native';
import { Text} from 'react-native-paper';

export default class App extends Component {
   constructor(props) {
    super(props);
    this.state = {
      data: [],
      isLoading: true,
      isSwitchOn: false,
      isMaintenanceSwitchOn: false,
      messagesReturned: [{
        key: '1',
        title: 'example title 1',
        subtitle: 'example subtitle 1',
      },
      {
        key: '2',
        title: 'example title 2',
        subtitle: 'example subtitle 2',
      },
      {
        key: '3',
        title: 'example title 3',
        subtitle: 'example subtitle 3',
      },],
    };
  }



 render() {
   
    return (
      <View style={styles.container}>
      <View style={{flexDirection:'row', alignItems:'flex-start', width: 350, height: 40, textAlign: 'left'}}>
       <Text style={styles.text}> Messages:    </Text>  
       </View >
       <SafeAreaView style={styles.safeareacontainer}>
        <ScrollView style={styles.scrollView}>
         <MessageList msgConst = {this.state.messagesReturned}/> 
        </ScrollView>
       </SafeAreaView>
      </View>
    );
 
  }
}

class  MessageList extends Component {
  render() {
   const listmessages = this.props.msgConst.map((msg) => 
     <Text>{msg.title}</Text>
    );
    return(
     {listmessages}
    );
  }
}

CodePudding user response:

Your MessageList component is trying to render an object - {listMessages}. If you remove the curly brackets it should work:

class  MessageList extends Component {
  render() {
   const listmessages = this.props.msgConst.map((msg) => 
     <Text>{msg.title}</Text>
    );
    // Change this line
    return listmessages;
  }
}
  • Related