The error “Objects are not valid as a React child” typically occurs when you try to render an object directly in your JSX. This issue commonly arises when trying to display complex data types, such as Date objects, without converting them to a format that React can render.
Let’s take an example of Timer,
The below code shows how we can display the elapsed time as a string. In code, this.state.timeElapsed is a Date object, which cannot be directly rendered in JSX. Instead, we need to convert it to a string.
import React from 'react'; import {TouchableHighlight, Text, View, StyleSheet} from 'react-native'; export class Timer extends React.Component { constructor(props) { super(props); this.state = { timeElapsed: null, isStarted: false, }; } handleStartPress() { if (!this.state.isStarted) { this.setState({isStarted: true}); setInterval(() => { this.setState({timeElapsed: new Date()}); }, 1000); } else { this.setState({timeElapsed: null, isStarted: false}); } } render() { const {timeElapsed, isStarted} = this.state; const elapsedTimeString = isStarted && timeElapsed ? timeElapsed.toISOString() : ''; return ( <View style={styles.container}> <View style={styles.timerContainer}> <Text>{elapsedTimeString}</Text> </View> <TouchableHighlight underlayColor="gray" onPress={() => this.handleStartPress()}> <Text>{this.state.isStarted ? 'Stop' : 'Start'}</Text> </TouchableHighlight> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, timerContainer: { marginVertical: 5, }, });
In this example, toISOString() is used to convert the Date object to a string. You can format the string further to display only the parts of the time you’re interested in.