I have backend in express and frontend in nextjs using shadcn
I have existing NewsArticle.tsx and NewsModal.tsx and UploadArticle.tsx
Now Can you design me NewsArticle.tsx such that article that I upload on backend is at the top and have bigger picture or card and other are smaller cards
and also define do that same and a icon above
also I have news from other resources that you can see in my newsController.js
make it look beutifull
// /app/components/NewsArticles.tsx
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { AlertCircle } from 'lucide-react'
import Image from 'next/image'
import { motion } from 'framer-motion'
import NewsModal from './NewsModal' // Ensure correct path
interface Article {
title: string
url: string
source: string
id: string
}
export default function NewsArticles() {
const [articles, setArticles] = useState<Article[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [selectedArticle, setSelectedArticle] = useState<Article | null>(null)
useEffect(() => {
const fetchArticles = async () => {
try {
const response = await fetch('http://localhost:5000/api/news/players/transfers') // Ensure correct endpoint
if (!response.ok) {
throw new Error('Failed to fetch news')
}
const data: Article[] = await response.json()
console.log('Fetched data:', data) // Debugging
setArticles(data)
} catch (error: any) {
console.error('Error fetching news:', error)
setError('Failed to load news. Please try again later.')
} finally {
setIsLoading(false)
}
}
fetchArticles()
}, [])
if (isLoading) {
return
}
if (error) {
return (
Error
{error}
)
}
return (
<>
Latest Transfer News
{articles.length > 0 ? (
articles.map((article) => (
<motion.div
key={article.id} // Use unique 'id' as the key
className="relative cursor-pointer rounded-lg overflow-hidden shadow-md"
whileHover={{ scale: 1.02 }}
onClick={() => setSelectedArticle(article)}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
>
{/* Placeholder Image */}
<Image
src="https://via.placeholder.com/400x200?text=News+Image" // Now allowed via next.config.js
alt={article.title}
width={400}
height={200}
className="w-full h-48 object-cover rounded-t-lg"
placeholder="blur"
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAIAAACt...==" // Optional: Update or remove
onError={(e: any) => {
e.target.onerror = null
e.target.src = 'https://via.placeholder.com/400x200?text=Image+Unavailable'
}}
/>
{article.title}
Source: {article.source}
</motion.div>
))
) : (
No articles available.
)}
{/* Modal for Detailed View */}
{selectedArticle && (
<NewsModal
article={selectedArticle}
onClose={() => setSelectedArticle(null)}
/>
)}
</>
)
}
// Skeleton Component for Loading State
function NewsSkeleton() {
return (
{[...Array(6)].map((_, index) => (
))}
)
}
// /app/components/NewsModal.tsx
'use client'
import { Dialog } from '@headlessui/react'
import { motion, AnimatePresence } from 'framer-motion'
import { X } from 'lucide-react'
import Image from 'next/image'
interface Article {
title: string
url: string
source: string
id: string
}
interface NewsModalProps {
article: Article
onClose: () => void
}
export default function NewsModal({ article, onClose }: NewsModalProps) {
return (
<Dialog.Overlay className="fixed inset-0 bg-black opacity-30" />
<motion.div
className="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all max-w-lg w-full relative"
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.8, opacity: 0 }}
transition={{ duration: 0.3 }}
>
<button
onClick={onClose}
className="absolute top-3 right-3 text-gray-500 hover:text-gray-700"
>
<X className="h-6 w-6" />
</button>
<div className="p-6">
<h2 className="text-xl font-bold mb-2">{article.title}</h2>
<p className="text-sm text-gray-600 mb-4">Source: {article.source}</p>
<div className="flex justify-center">
<Image
src="https://via.placeholder.com/400x200?text=News+Image" // Ensure this domain is configured
alt={article.title}
width={400}
height={200}
className="object-cover rounded-md"
onError={(e: any) => {
e.target.onerror = null
e.target.src = 'https://via.placeholder.com/400x200?text=Image+Unavailable'
}}
/>
</div>
</div>
<div className="px-6 pb-6 flex justify-end">
<a
href={article.url}
target="_blank"
rel="noopener noreferrer"
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
>
Read Full Article
</a>
</div>
</motion.div>
</div>
</Dialog>
</AnimatePresence>
)
}
// /app/components/TopNews.tsx
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { AlertCircle } from 'lucide-react'
import Image from 'next/image'
import { motion } from 'framer-motion'
import NewsModal from './NewsModal'
import placeholderImage from '/public/placeholder.png' // Add a placeholder image in public folder
interface Article {
headLine: string
url: string
source: string
}
interface TopNewsResponse {
club: string
topPlayers: Article[]
}
export default function TopNews() {
const [articles, setArticles] = useState<Article[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [selectedArticle, setSelectedArticle] = useState<Article | null>(null)
useEffect(() => {
const fetchTopNews = async () => {
try {
const response = await fetch('http://localhost:5000/api/articles') // Adjust the endpoint if necessary
if (!response.ok) {
throw new Error('Failed to fetch top news')
}
const data: TopNewsResponse = await response.json()
setArticles(data.topPlayers)
} catch (error) {
console.error('Error fetching top news:', error)
setError('Failed to load top news. Please try again later.')
} finally {
setIsLoading(false)
}
}
fetchTopNews()
}, [])
if (isLoading) {
return
}
if (error) {
return (
Error
{error}
)
}
return (
<>
Top News
{['RealMadrid', 'Barcelona'].map((club) => (
<motion.div
key={club}
className="relative cursor-pointer rounded-lg overflow-hidden shadow-lg"
whileHover={{ scale: 1.02 }}
onClick={() => {
const clubArticle = articles.find(a => a.headLine.toLowerCase().includes(club.toLowerCase()))
if (clubArticle) setSelectedArticle(clubArticle)
}}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
>
<Image
src={club === 'RealMadrid' ? '/RealMadrid.png' : '/Barcelona.png'} // Ensure these images exist in /public
alt={${club} Logo}
width={200}
height={200}
className="w-full h-40 object-cover"
placeholder="blur"
blurDataURL="/placeholder.png"
/>
{club}
</motion.div>
))}
{/* Other Clubs Placeholder */}
<motion.div
className="relative cursor-pointer rounded-lg overflow-hidden shadow-lg bg-gray-200 flex items-center justify-center"
whileHover={{ scale: 1.02 }}
>
<p className="text-center text-gray-500">Other Clubs Coming Soon</p>
{/* Add a loading spinner or placeholder if desired */}
</motion.div>
</div>
</CardContent>
</Card>
{/* Modal for Detailed View */}
{selectedArticle && (
<NewsModal
article={selectedArticle}
onClose={() => setSelectedArticle(null)}
/>
)}
</>
)
}
function TopNewsSkeleton() {
return (
Top News
{[...Array(2)].map((_, index) => (
))}
{/* Placeholder for Other Clubs */}
<Skeleton className="w-full md:w-1/2 h-40 rounded-lg" />
</div>
</CardContent>
</Card>
)
}
// /app/components/UploadArticle.tsx
'use client'
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Button } from "@/components/ui/button"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
export default function UploadArticle() {
const [formData, setFormData] = useState({
title: '',
content: '',
author: '',
})
const [image, setImage] = useState<File | null>(null)
const [status, setStatus] = useState<{ type: string; message: string } | null>(null)
const [isUploading, setIsUploading] = useState(false)
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value })
}
const handleImageChange = (e: React.ChangeEvent) => {
if (e.target.files && e.target.files[0]) {
setImage(e.target.files[0])
}
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setIsUploading(true)
setStatus(null)
const data = new FormData()
data.append('title', formData.title)
data.append('content', formData.content)
data.append('author', formData.author)
if (image) {
data.append('image', image)
}
try {
const res = await fetch('/api/uploadArticle', {
method: 'POST',
body: data,
})
if (!res.ok) {
const errorData = await res.json()
throw new Error(errorData.error || 'Something went wrong')
}
const result = await res.json()
setStatus({ type: 'success', message: 'Article uploaded successfully!' })
setFormData({ title: '', content: '', author: '' })
setImage(null)
} catch (error: any) {
console.error('Error uploading article:', error)
setStatus({ type: 'error', message: error.message || 'Failed to upload article' })
} finally {
setIsUploading(false)
}
}
return (
Upload New Article
{status && (
<Alert variant={status.type === 'error' ? 'destructive' : 'success'}>
{status.type === 'error' ? 'Error' : 'Success'}
{status.message}
)}
<form onSubmit={handleSubmit} className="space-y-4 mt-4">
<div>
<label className="block text-sm font-medium text-gray-700">Title</label>
<Input
type="text"
name="title"
value={formData.title}
onChange={handleChange}
required
placeholder="Enter article title"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Content</label>
<Textarea
name="content"
value={formData.content}
onChange={handleChange}
required
placeholder="Enter article content"
rows={5}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Author</label>
<Input
type="text"
name="author"
value={formData.author}
onChange={handleChange}
required
placeholder="Author name"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Image</label>
<input
type="file"
name="image"
accept="image/*"
onChange={handleImageChange}
className="mt-1 block w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 cursor-pointer focus:outline-none"
/>
{image && <p className="text-sm text-gray-500 mt-1">{image.name}</p>}
</div>
<div>
<Button type="submit" disabled={isUploading}>
{isUploading ? 'Uploading...' : 'Upload Article'}
</Button>
</div>
</form>
</CardContent>
</Card>
)
}
[
{
"id": "article-id-1",
"title": "",
"headingImage": "",
"content": "# Ole Gunnar Solskjaer Rejection Pays Off After £83.5m Man Utd Transfer Fell Through\r\n\r\nManchester United's transfer policy during Ole Gunnar Solskjaer's time in charge came under plenty of scrutiny, but there's been less noise about the deals they failed to complete.\r\n\r\nDate: 25 Sep 2024\r\n\r\nManchester United offered a huge £83.5 million for Ansu Fati in 2020, it has been claimed, but the forward's injury problems since might make some consider it a bullet dodged.\r\n\r\nFati, a star at Barcelona as a teenager, became the club's youngest-ever La Liga scorer when he found the net before his 17th birthday. He ended his first season at Camp Nou with eight goals in all competitions and would go on to make his senior Spain debut at 17.\r\n\r\nUnited entered the summer of 2020 off the back of a third-place finish, only sealing Champions League qualification on the final day of the season. However, manager Ole Gunnar Solskjaer was left frustrated in his pursuit of new signings.\r\n\r\nJadon Sancho was a top target for United that year, but wouldn't arrive from Borussia Dortmund for another 12 months. That led them to look at Fati, but it wasn't to be.\r\n\r\nThe £83.5 million figure comes from The Athletic, while reports at the time suggested they were prepared to go even higher. Instead, though, Barcelona were able to fend off interest and tie Fati down to a long-term deal with a mammoth £363 million release clause.\r\n\r\n> “We are enjoying life at Barcelona,” Fati's father Bori told El Larguero at the time. “But my son must be patient for his chances, as he is playing with the greatest footballer ever in Lionel Messi.\r\n\r\n> “The United links are not true, Ansu is happy here, he is following his dreams. He does not have to start every game, and he has Griezmann and Suarez ahead of him. Ansu has a lot of time.”\r\n",
"author": "Suraj Singh",
"isUserArticle": true
}
]
This is the response from api on url api/articles