Skip to content
Advertisement

Issues with conditional rendering react

So I have read quite a lot about react conditional rendering on the official docs and on STO as well but I have some issues and doubts.

     return (
        
        <div className="container is-fluid">
          {games.map((game) => (
            
           <div className="gameContainer" key={game.id}>
             
    
        {!!`${game.live_embed_url}` && (<iframe src= {`${game.live_embed_url}&parent=localhost`} frameBorder="2" allowFullscreen="true" scrolling="no" height="378" width="620">
</iframe>)}
    
    
            <h2 className="h2__whiteuk-text-large">{game.name}{game.live_embed_url}</h2>
            </div>
          ))}
        </div>
      );

My objective here is I’m trying to check if the value of {game.embed_url} is NULL then no <iframe> should be rendered, else <iframe> should be rendered,

Ofc all this would be much simpler with a if/else but since I’m inside the return I cannot use that and I’m not sure how to proceed with this.

I’m sorry if the question is too basic but I have spent too much time trying to figure it out and just keep breaking my application.

Advertisement

Answer

I believe you need to use the ternary operator in this type of situation:

{
game.live_embed_url ?
    (<iframe src= {`${game.live_embed_url}&parent=localhost`} frameBorder="2" allowFullscreen="true" scrolling="no" height="378" width="620">
</iframe>) 
    : null
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement