Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  155] [ 7]  / answers: 1 / hits: 6341  / 4 Years ago, mon, march 23, 2020, 12:00:00

Hi I am student developer at ReactJS platform. I used class component before with render method but now I am learning hooks and function components are so important for it like every Reactjs developer know. I have a problem while using nested components and I am facing an error like this :




index.js:1 Warning: Functions are not valid as a React child. This may
happen if you return a Component instead of from render.
Or maybe you meant to call this function rather than return it




Could you help me at this issue ? How can I use stateless function components in my return part efficiently ?



My sample nested components code :



import React, {useContext} from 'react';
import { BookContext } from '../../contexts/BookContext';
import BookDetails from './BookForm';


const BookList = (props) => {
const {books} = useContext(BookContext);

const emptyBooks = ()=>{
return (
<div className=empty>
No books to read. Let's read now. You are free!
</div>
)
}


const notEmptyBooks=()=>{
return (
<div className=book-list>
<ul>

{books.map(book=>{
return (

<BookDetails books={books} key={book.id}></BookDetails>
)
})}

</ul>
</div>
)
}

// it does not work. I think error is here
return books.length>0?()=>emptyBooks:()=>notEmptyBooks

}

export default BookList;

More From » reactjs

 Answers
2

You need to call those functions. In your original code you technically just returned the function definition with () => emptyBooks. So your assumption was right the error happened there.



Try the following code snippet instead:



return books.length > 0 ? emptyBooks() : notEmptyBooks()


I hope this helps!


[#4402] Friday, March 20, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;