49
votes

I am getting an below error. I can see that I have to return array instead of object. But I am really not sure how to fix it. Thanks in advance

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of View.

constructor(props){
    super(props);
    this.state = {timeElapsed: null};
  }

startStopButton(){
    return <TouchableHighlight underlayColor="gray" onPress={this.handleStartPress.bind(this)}>
        <Text>Start</Text>
      </TouchableHighlight>
  }

handleStartPress(){
      var startTime = new Date();




      setInterval(()=>{
        this.setState({timeElapsed: new Date()})
      }, 1000);
  }
render(){
return(
  <View style={styles.container}>
    <View style={[styles.header]}>
      <View style={[styles.timerContainer, this.borderColor('#ff6666')]}>
        {this.state.timeElapsed}
      </View>
      <View style={[styles.buttonsContainer, this.borderColor('#558000')]}>
        {this.startStopButton()}
        {this.lapButton()}
      </View>
    </View>
  </View>
);


}
3
Can you show your render method? - Nader Dabit
You're not showing anything that can help us debug it, the render method would be where I start. - theBrezilien
Hi I have just added render method. Thanks - Mesmerize86
what is your styles containing? - A. L
I am also getting the same error for github.com/kushmpatel/auth_React_Demo this demo. Can you please checkout this project and check it? I am learning react native and seriously have no idea where is the problem in my code? - Kush Patel

3 Answers

58
votes

timeElapsed is an object, React doesn't know how to render this:

  <View style={[styles.timerContainer, this.borderColor('#ff6666')]}>
    {this.state.timeElapsed}
  </View>

Try changing this.state.timeElapsed for a string like for example:

  <View style={[styles.timerContainer, this.borderColor('#ff6666')]}>
    {this.state.timeElapsed.toString()}
  </View>
1
votes
<Note note={
 <p>{(new Date(updated_at)).toString()}</p>
} />

In this case, Note is my child component and I had passed date as above and it worked for me.

Output Pass date to React Child

0
votes
  • Short & simple is that use JSON.stringify()
  • because this.state.timeElapsed is the object. object not able to print in normal standered. Thus we need to render that object in JSON.stringify(). It converted into JSON form.

  • Try this, It's work for me

{JSON.stringify(this.state.timeElapsed)}