Home > other >  How to display a message inside an empty div when a component doesn't render in it?
How to display a message inside an empty div when a component doesn't render in it?

Time:09-25

I have a div inside which I'm rendering dynamic card components(SearchRes):

<div className="search-res">
            {games.filter(game => (game.background_image !== null)&&(game.ratings_count>38)).map(game=>
            <SearchRes
            key={game.name} 
            title={game.name} 
            rating={game.metacritic===null?<MdGamepad/>:game.metacritic} 
            genre={game.genres.map(genre=>genre.name " ")} 
            imglnk={(game.background_image===null)?"":game.background_image}
            gameid={game.id}
            slug={game.slug}
            plat={game.parent_platforms}
            />
            )}
 </div>

When the cards don't render (when they don't pass the filter conditions), I get a blank space. I want to display something like no results found when such thing happens, how can I implement this? Currently I'm using CSS to implement it:

.search-res:empty::before {
content: "No data";}

but clearly this is not viable as the message is visible when the search is not even initiated: message displayed when search isn't even initiated

CodePudding user response:

I would suggest to filter the array first, based on the conditions and then check if the array has length i.e. arr.length !== 0 and if that is the case, then map the results of the array to the card component. And if not then show the message that no data found. You would have to use if/else or ternary operator.

Thanks

  • Related