Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting Warning: Functions are not valid as a React child?

Tags:

When I try to call a method which returns the result of the map method, I get the following error Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render but I don't know why. Here is my code:

renderAlbums() {         return this.state.albums.map(album => <Text>{ album.title }</Text>);     }      render() {         return (             <View>                 { this.renderAlbums }             </View>         );     } 

But I the code above I don't see where the problem comes from. But when I try to create a variable in my render() method in which a pass my map() method,everything works good:

render() {   const c=this.state.albums.map(album => <Text>{ album.title }</Text>);     return (         <View>             { c }         </View>     ); } 

I would like to understand why it doesn't work. When I call the render renderAlbums() method here <View>{ this.renderAlbums }</View>.

And And what seems even weirder to me is that when I try to call the renderAlbums() like this <View>{ this.renderAlbums() }</View> with parentheses it works.

like image 877
Christian Lisangola Avatar asked Aug 01 '18 05:08

Christian Lisangola


People also ask

How do you fix error objects are not valid as a React child?

js error "Objects are not valid as a React child" occurs when we try to directly render an object or an array in our JSX code. To solve the error, use the map() method to render arrays or access properties on the object in your JSX code.

Why objects are not valid as React child?

The "Objects are not valid as a React child" error happens when trying to render a collection of data by mistakenly returning the object when applying the map method instead of using the data from the object to create and return JSX.

What is a child element in React?

children is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component. These kinds of components are identified by the official documentation as “boxes”.


1 Answers

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render

Basically,React expecting the React Elements to render it.

In current script,this.renderAlbums is a function reference which not returning any React Element.Function itself not react element.So,React unable to render the this.renderAlbums.

<View>    { this.renderAlbums } </View> 

correct way:

<View>    { this.renderAlbums() } //it will return react element which can be rendered. </View> 
like image 71
RIYAJ KHAN Avatar answered Sep 27 '22 20:09

RIYAJ KHAN