I've been trying for a couple of days to fix this problem but I really can't seem to figure it out.
I am trying to develop a Blog in React, I have created a 'Data.jsx' file which contains all the information of each post. A thing like that:
import POST from '../../assets/blog-post.jpg'
const Data = [
{
id: 1,
image: POST,
title: 'This is my first post!',
github: 'https://github.com',
read: '/Blog/buymeanr6please'
},
{
id: 2,
image: POST,
title: '2',
github: 'https://github.com',
read: 'https://gitlba.com'
},
{
id: 3,
image: POST,
title: '3',
github: 'https://github.com',
read: 'https://gitlba.com'
},
{
id: 4,
image: POST,
title: '4',
github: 'https://github.com',
read: 'https://gitlba.com'
},
{
id: 5,
image: POST,
title: '5',
github: 'https://github.com',
read: 'https://gitlba.com'
},
{
id: 6,
image: POST,
title: '6',
github: 'https://github.com',
read: 'https://gitlba.com'
}
]
export default Data
Now, I want to create a preview of the last 3 posts (so of 4, 5, 6) but I can't work with the array in the other file. All 6 posts are shown.
import React from 'react'
import './blogPreview.css'
import Data from '../blog/Data'
import {useNavigate} from 'react-router-dom'
const BlogPreview = () => {
let navigate = useNavigate()
return (
<section id='blogPreview'>
<h5>My Recent Post</h5>
<h6 onClick={() => {navigate("/Blog")}}>(yea i also have a blog, check it out!)</h6>
<h2>Blog</h2>
<div className="container blogPreview__container">
{
Data.map(({id, image, title, github, read}) => {
return(
<article key={id} className='blogPreview__item'>
<div className="blogPreview__item-image">
<img src={image} alt={title} />
</div>
<h3>{title}</h3>
<div className="blogPreview__item-cta">
<a href={read} className='btn btn-primary'>Read</a>
<a href={github} className='btn' target='_blank'>Github</a>
</div>
</article>
)
})
}
</div>
</section>
)
}
export default BlogPreview
I know it might be a bit confusing, I hope I explained myself well, if it helps this is link of the updated repo.
CodePudding user response:
You can use Data.slice(3).map()
This will start ignoring the first three elements of the array
CodePudding user response:
If the raw data is not structured then sort that data by id
or any other appropiate field first then apply slice to extract elements.
To sort in descending order by id
data = data.sort((a, b) => parseFloat(b.id) - parseFloat(a.id));
then take first 3 objects from data array
data = data.slice(0, 3);
If your data is strcutured and you are sure the latest elements comes always at end, then use slice(-n)
to extract last n objects.
data = data.slice(-3);
CodePudding user response:
I'm not an expert, but have you tried running the Data on a different Port? So just run the jsx-file on e.g. localhost:3001, then fetching the data using GET-Requests