I have a custom repository API, I want to showcase it in my Next.js
web app. But if an empty field is found in the API, I want to skip that element.
My API:
{
"myrepo": [
{
"name": "Lorem Ipsum 1",
"description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"language": "TypeScript",
"html_link": "https://example.com/project1",
"homepage": "https://projectdomain1.com"
},
{
"name": "Lorem Ipsum 2",
"description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"language": "JavaScript",
"html_link": "https://example.com/project2",
"homepage": ""
},
{
"name": "Lorem Ipsum 3",
"description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"language": "C#",
"html_link": "https://example.com/project3",
"homepage": "https://projectdomain3.com"
}
]
}
ProjectCard.tsx
import useSWR from 'swr';
import fetcher from 'lib/fetcher';
import type { Repos } from 'lib/types';
export default function ProjectsCard() {
const { data, error } = useSWR<Repos>('/api/repo', fetcher);
if (error) {
return <div>Failed to load</div>;
}
if (!data) {
return <div>Loading...</div>;
}
return (
<>
{data.myrepo.map((repo, index) => (
<div key={index} className="mb-8">
<p className="text-gray-900 font-medium">
1. Project Name: {repo.name}
</p>
<p className="text-gray-900 font-medium">
2. Project Description: {repo.description}
</p>
<p className="text-gray-900 font-medium">
3. Project Link: {repo.html_url}
</p>
{repo.homepage !== '' && (
<p className="text-gray-900 font-medium">
4. Project Homepage: {repo.homepage}
</p>
)}
<p className="text-gray-900 font-medium">
5. Project Language: {repo.language}
</p>
</div>
))}
</>
);
}
4. Project Homepage:
not hide for 2nd child.
I want to completely remove the 4. Project Homepage:
element if homepage return blank.
I want the final output look like this:
For 1st
1 Project Name: ....
2 Project Description: ....
3 Project Link: ....
4 Project Homepage: ....
5 Project Language: ....
For 2nd (Check it, No. 4 is not here)
1 Project Name: ....
2 Project Description: ....
3 Project Link: ....
5 Project Language: ....
For 3rd
1 Project Name: ....
2 Project Description: ....
3 Project Link: ....
4 Project Homepage: ....
5 Project Language: ....
CodePudding user response:
Try to check length of string:
repo.homepage !== ''
&& repo.homepage != undefined
&& repo.homepage?.length < 1 && (
// other code is omitted for th ebrevity