How to have backup URL show if the JSON data is undefined? - reactjs

const SearchResults = ({ artists }) => (
<div className="search-results">
{artists.map(val => (
<a href="# " key={uniqid()}>
<h3>{val.name}</h3>
<img
className="box-img"
src={
val.images[0].url
? val.images[0].url
: 'https://www.w3schools.com/w3css/w3css_images.asp'
}
alt=""
/>
</a>
))}
</div>
);
I have an API call going to Spotify to get a list of Artist. When the results all have an image there is no problem but if they don't, React just returns undefined and I can't figure out how to have the placeholder image show.

You can simply have a bare png default image for this in your project, then import it and use it when no image is returned from spotify, something like:
import defaultArtistImage from './myProject/assets/images/defaultArtistImage.png';
...
const SearchResults = ({ artists }) => (
<div className="search-results">
{artists.map(val => (
<a href="# " key={uniqid()}>
<h3>{val.name}</h3>
<img
className="box-img"
src={
val.images.length !== 0
? val.images[0].url
: defaultArtistImage
}
alt=""
/>
</a>
))}
</div>
);
this is simpler than retrieving the image from an external server. Also, doing val.images[0].url can give you an error if .images it's an empty array

Related

Objects are not valid as a React child found: object with keys {id, type} If you meant to render a collection of children, use an array instead

i want to display categories and thier questions, from database as api throught flask and react app. i got that error all the recat app that contain list, add and play questions. i think the porblem is the side of the react app. the flask api display json format correctly. any help guys
python ( flask)
#app.route("/categories/<int:category_id>/questions", methods=['GET'])
def get_question_based_category(category_id):
question_based_category=Question.query.filter(Question.category==str(category_id)).all()
formatted_questions=[]
questions_per_page=10
page=request.args.get('page',1,type=int)
start=(page-1)*questions_per_page
end=start+questions_per_page
for searchquestion in question_based_category:
formatted_questions.append(searchquestion.format())
return jsonify({
'success':True,
'question':formatted_questions[start:end],
'total_of _searched_question':len(question_based_category),
'current_category':searchquestion.category
})
create js
render() {
return (
<div className='question-view'>
<div className='categories-list'>
<h2
onClick={() => {
this.getQuestions();
}}
>
Categories
</h2>
<ul>
{Object.keys(this.state.categories).map((id) => (
<li
key={id}
onClick={() => {
this.getByCategory(id);
}}
>
{this.state.categories[id]}
<img
className='category'
alt={`${this.state.categories[id].toString().toLowerCase()}`}
src={`${this.state.categories[id].toString().toLowerCase()}.svg`}
/>
</li>
))}
</ul>
<Search submitSearch={this.submitSearch} />
</div>
<div className='questions-list'>
<h2>Questions</h2>
{this.state.questions.map((q, ind) => (
<Question
key={q.id}
question={q.question}
answer={q.answer}
category={this.state.categories[q.category]}
difficulty={q.difficulty}
questionAction={this.questionAction(q.id)}
/>
))}
<div className='pagination-menu'>{this.createPagination()}</div>
</div>
</div>
);
}

Display dynamic multiple image if only present

My backend API have mulitple file upload. User can have choice to upload one image or multiple or none. So, image array may be length 0, 1 or more.
Scenerio:
endpoint api/v1/img/1 may have gallery img1, img2, img3
endpoint api/v1/img/2 may have gallery img1
endpoint api/v1/img/3 may have gallery null
{ gallery.img_urls?.map((img, i) => (
<div key={i}>
<img src={img} alt="gallery" />
</div>
))}
It is displaying mulitiple image. But if image isn't present it raise an error
ref3.map is not a function
if don't want anything when no image or any error to render image then you can use
{ gallery.img_urls?.map((img, i) => (
<div key={i}>
<img src={img} alt="gallery" onerror="this.onerror=null; this.remove()" />
</div>
))}
OR you can set the default image src value or also if you don't want the default image then add simply null value in src.
{ gallery.img_urls?.map((img, i) => (
<div key={i}>
<img src={img} alt="gallery" onerror="this.onerror=null; this.src='Default.jpg'" />
</div>
))}

Cannot generate and dispaly PDF with React-PDF library

I am trying to generate pdf of below React component
function DocumentPrint() {
return (
<div className="container">
<h1 className="heading__main">This is a demo heading</h1>
<div>
<h3 className="heading__title">This is another heading</h3>
<p className="para__text">Breakable components try to fill up the remaining space before jumping into a new page. By default, this group is composed by View, Text and Link components
Unbreakable components are indivisible, <b>therefore</b> if there isn't enough space for them they just get rendered in the following page. In this group by default we only find Image.</p>
</div>
<div id="unordered__list">
<ul className="list">
<li>Amit</li>
<li>Suraj</li>
<li>Priya</li>
</ul>
</div>
</div>
)
}
const Doc = () => {
return (
<div>
<PDFDownloadLink
document={<DocumentPrint />}
fileName="somename.pdf"
>
{({ blob, url, loading, error }) =>
loading ? <button>Loading document...</button> : <button>Download now!</button>
}
</PDFDownloadLink>
</div>
)
}
This is not showing Download now button and loading is not set to false.
Error in console
TypeError: Cannot read properties of undefined (reading 'height') at setNodeHeight

How to display an image?

I can not display the image, I do
const imgUrl = companyList.find(i => i.id === items.companyId).imgUrl;
And after creating the block, the desired picture is displayed, but it is worth updating the page, as ...
Everything is normally added to the database and should work ...
In my other file, I use the exact same method and everything works, but for some reason there isn’t ...
const getInvoiceList = () => {
return invoiceList.map(items => {
const imgUrl = companyList.find(i => i.id === items.companyId).imgUrl;
return (
<div key={items.id} className="invoice__card">
<div className="card__data">
<p>{items.invoice}</p>
<i onClick={() => onVisibleDetails(items.id)}><FiMoreHorizontal /></i>
</div>
<div className="card__body">
<div className="invoice__order">
<p>Оплатил</p>
<img src={imgUrl} alt="logo" />
</div>
<div className="invoice__order">
<h3>$2.400</h3>
<p>Сумма</p>
</div>
<div className="invoice__date">
<h3>30.01.2020</h3>
<p>Дата оплаты</p>
</div>
</div>
</div>
);
});
};
<div className="invoice__card-wrapper">
{invoiceList.length !== 0 ? getInvoiceList() : "Nety"}
</div>
Looks like your data is either incomplete, or the structure isn't matching up with the way you're trying to access it. The error Cannot read property "imgUrl" is occurring because your find() method call is not finding an object, so the imgUrl property isn't defined.
This will keep the error from occurring:
const imgUrl = (companyList.find(i => i.id === items.companyId) || {}).imgUrl;
If you want to add more info about where the companyList is coming from, we might be able to get closer to an answer.

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
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 ''.

Resources