Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected token in conditional rendering in React

I’m trying to make the following code work but I’m getting a syntax error after the displayPosts(posts); call: Unexpected token, expected "{"

{hasPostsResolved && posts?.length > 0 &&
    displayPosts(posts);
    <input type="button" className="wp-element-button" value="Load More" />
}

For completeness:

const { posts, hasPostsResolved } = useSelect(select => {
    const query = {
        order: 'desc',
        orderby: 'date',
        status: 'publish',
        categories: category ? category : [],
        per_page: number
    };
    return {
        posts: select('core').getEntityRecords('postType', 'post', query),
        hasPostsResolved: select('core').hasFinishedResolution('getEntityRecords', ['postType', 'post', query]),
    }
}, [category, number]);

const displayPosts = (posts) => {
    return (
        posts.map((post, index) => {
            return (
                <article id={`post-${post.id}`} key={index}>
                    <h2>
                        {
                            post.title.rendered ?
                            decodeEntities(post.title.rendered) :
                            __('(no title)')
                        }
                    </h2>
                    <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
                </article>
            )
        })
    )
};

Can someone tell what’s wrong with my code? I can’t make it work for the life of me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Maybe you meant the following? I’m assuming that displayPosts is a function that returns JSX.

{hasPostsResolved && posts?.length > 0 &&
    <>
        {displayPosts(posts)}
        <input type="button" class="wp-element-button" value="Load More" />
    </>
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading