I've fetched an array of news articles from an api which is in the newsArticles state.
I map over the state and deconstruct the data that I need. I then pass the title and description props to the card. Then I've got a modal that's hidden using CSS and I pass the title and content prop to the modal.
My problem is that when I open the modal, the correct title and content isn't displaying. Regardless which article I click on, when I open the modal it only displays the title and content of the last article in the array. It should display the correct title and content for the card that has been cliced on.
Why is this happening? My code is below. Thanks.
import React, { useState } from 'react';
import { useNewsContext } from '../context/news-context';
const NewsCard = () => {
const { newsArticles, isLoading } = useNewsContext();
const [isModalOpen, setIsModalOpen] = useState(false);
const readMore = () => {
setIsModalOpen(true);
};
const closeBtn = () => {
setIsModalOpen(false);
};
return (
<section className='news-section wrapper'>
{' '}
{newsArticles.map((item, index) => {
const { title, description, urlToImage, content } = item;
return (
<div key={index} className='news-card'>
<img className='news-image' src={urlToImage} alt={title} /> <h1> {title} </h1>{' '}
<p> {description} </p>{' '}
<button type='button' onClick={readMore}>
{' '}
Read More{' '}
</button>{' '}
<div className={isModalOpen ? 'news-modal' : 'news-modal news-modal__hidden'}>
<div className='news-modal__card'>
<h1> {title} </h1> <p> {content} </p>{' '}
<button type='button' onClick={closeBtn}>
{' '}
Close{' '}
</button>
</div>{' '}
</div>{' '}
</div>
);
})}{' '}
</section>
);
};
export default NewsCard;