0

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

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I understand now.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.