Why Am I Getting Warning: Functions Are Not Valid as a React Child?
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...
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.
4 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>
this.renderAlbums refers to the actual function itself, whereas this.renderAlbums() actually executes the function and thus represents the function's return value.
I think i should share my experience about this error, my code:
const PageMakeup = loading ? ThemLoading : (
<div>....</div>
);
The problem here is ThemLoading is include in other file, should be <ThemLoading />;
And this error is cleared!
About your error: Callback function and return function is diffirent, in your case is the return funtion this.renderAlbums();, not this.renderAlbums;
Good day!
Instead of pointing to the function return the whole function
return (
<View>
{ this.renderAlbums() }
</View>
);