0
votes

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;
2

2 Answers

2
votes

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!

1
votes

You are returning a function instead of jsx, hence the error. A react component should always return jsx.

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

This should solve your problem.