FairyQueen
FairyQueen

Reputation: 2373

Why am I getting an 'Objects are not valid as a React child' in React Native?

I am passing an array to a FlatList but I am getting an errror:

'Invariant Violation: Objects are not valid as a React child (found: object with keys {id, customer, etc}).

I've tried putting brackets around item and removing them but nothing is working. Does anyone know how to fix this error?

renderSearches = () => {
    if (this.state.products.length) {
        return (
            <View style={styles.suggestionContainer}>
                <FlatList
                    data={this.state.products}
                    keyExtractor={(item, index) => index.toString()}
                    renderItem={({item}) => <SuggestionItem value={item} onSelect={this.updateSearchTerm} />}
                />
            </View>
        )
    }

    return (<View></View>);
}

here is the SuggestionItem render:

render() {
    const {value} = this.props;
    return (
        <TouchableOpacity style={styles.suggestion} onPress={() => {this.props.onSelect(value)}}>
            <Text style={styles.suggestionText}>{value}</Text>
        </TouchableOpacity>
    );
}

enter image description here

enter image description here

Upvotes: 1

Views: 9600

Answers (4)

Ibrahim
Ibrahim

Reputation: 1

in my case i had an array of object in my data collection which i didn't know until i added 'toString()' like this {room.data.name.toString()},after deleting the object in my data collection i then remove 'toString()' and the problem was solved

Upvotes: 0

akshay gore
akshay gore

Reputation: 1006

Your SuggestionItems render method should have -

<Text style={styles.suggestionText}>{value.customer}</Text>

or something like

<Text style={styles.suggestionText}>{value.name}</Text>

instead of directly rendering the whole object in a text component

<Text style={styles.suggestionText}>{value}</Text>

Upvotes: 8

BigPun86
BigPun86

Reputation: 2686

Like the red box is telling you :) You are rendering a object with keys, in your case value is an object which looks like this =>

value: {
    id: "1234"
    customer: "0"
    ........
}

In other words your array which you are passing to your FlatList is an Array with Objects...So you have to choose which object property you want to display in your Text component

render() {
  const {id, customer, perm_override, order_count, cost_flag .....} = this.props.value;
  return (
    <TouchableOpacity style={styles.suggestion} onPress={() => {this.props.onSelect(value)}}>
        <Text style={styles.suggestionText}>{customer}</Text>
    </TouchableOpacity>
  );
}

Upvotes: 1

Vipul Singh
Vipul Singh

Reputation: 646

value is an object which you're passing to Text element. It should be string not an object. For example:

<Text style={styles.suggestionText}>{value.cutomer}</Text>

Upvotes: 0

Related Questions