Home > Enterprise >  React Native Render Error - Error: Objects are not valid as a React child
React Native Render Error - Error: Objects are not valid as a React child

Time:10-30

when I add the card component to app.js it shows the below error:

( Error: Objects are not valid as a React child (found: an object with keys {}). If you meant to render a collection of children, use an array instead ).

I did not add any objects to add keys. In the AppText component I have passed only the children props and used them as title and subtitles in the Card component

import React from 'react';
import Card from './app/components/Card';
import {View} from 'react-native';

export default function App() {
  return (
    <View
      style={{
      backgroundColor: '#f8f4f4',
      padding: 20,
      paddingTop: 100,
    }}>
      <Card
        title="Item 1"
        subTitle="$50 Million"
        image={require('./app/assets/image/card-img1.jpg')}
      />
   </View>
 );
}

this is the card component code

import React from 'react';
import {Image, StyleSheet, View} from 'react-native';
import colors from '../config/colors';
import AppText from './AppText';

function Card(image, title, subTitle) {
  return (
    <View style={styles.card}>
      <Image source={image} />
      <AppText>{title}</AppText>
      <AppText>{subTitle}</AppText>
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    borderRadius: 15,
    backgroundColor: colors.white,
    marginBottom: 20,
  },
});

export default Card;

this is the AppText component

import React from 'react';
import {Text, StyleSheet, Platform} from 'react-native';
import colors from '../config/colors';

function AppText({children}) {
  return <Text style={styles.text}>{children}</Text>;
}

const styles = StyleSheet.create({
  text: {
    color: colors.black,
    ...Platform.select({
      ios: {
        fontSize: 20,
        fontFamily: 'Avenir',
      },
      android: {
        fontSize: 18,
        fontFamily: 'Roboto',
      },
    }),
  },
});

export default AppText;

CodePudding user response:

A simple change, make it work!

change your Card component definition from:

function Card(image, title, subTitle) {

to

function Card({image, title, subTitle}) {

Explanation:

When you want to pass property to a component, the input parameter of your component will be porps, if you want to destruct these props, you need to put a {} (the props is an object):

const myObject = {name: 'testName', title: 'testTitle'}

const {name, title} = myObject

CodePudding user response:

In your Card functional component, you should destructure the props that are passed to it.

In addition, the order of the props in declaration and usage should coincide with each other.

Changes

From:

function Card(image, title, subTitle)

To:

function Card({title, subtTitle, image})
  • Related