Home > OS >  render default src img if there is no image data fetched from database in react js
render default src img if there is no image data fetched from database in react js

Time:04-15

i`m trying to render a component, which if there is no fetched data from database it will render the imported image, this is my code.

import userDefault from '../../../assets/userDefault.png
<img src={profile?userPhoto ? profile?.userPhoto : userDefault} alt="User-Image" />

how can i render userDefault if the profile.userPhoto value is null?

CodePudding user response:

Your implementation looks fine to me, just sharing the improved code below

JSX

<img src={profile?.userPhoto ? profile.userPhoto : userDefault} alt="User-Image" />

2nd Approach Using OR Operator (||)

JavaScript OR Operator tries to find first truthy value so if database image exists then it will render it, if not then it will render your default image

JSX

<img src={profile?.userPhoto || userDefault} alt="User-Image" />
  • Related