gamer
gamer

Reputation: 5863

react if data present else something else in component

I have a react component that is like :

class List extends Component {
  render() {
    const {infos} = this.props
    var info;
    if(infos.user_info ){
      info = infos.user_info.filter(inf => inf.id).map((inf =>{
        return <div className={"inf"} style={{height:"300px", width:"300px"}} key={inf.id} >
                  <p>{ inf.name }</p>
                  <img src={inf.thumbnail} height="250px" width="250px" />
                </div>

      }))
    }


    return (
      <div> {info} </div>
      )
  }
}

export default List

Here I have problem with image part. I want to display the information of user with image. Here not all the user info might have images. Some have null value too.

<img src={inf.thumbnail} height="250px" width="250px" /> Here I want to display the thumbnail if it is available else I want to display some random picture..

I hope you guys understand.. How can I do this ??

Thank you

Upvotes: 0

Views: 120

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

You can use the conditional operator.

inf.thumbnail ?
  <img src={inf.thumbnail} height="250px" width="250px" /> :
  <img src="something-else.png" />

This will only show the thumbnail if inf.thumbnail is not undefined, null, false or ''.

Upvotes: 1

Related Questions