The code below generates a list of post titles. My intention is that when I click on a title, the list disappears and the post content is shown. What happens is that when I click on a title, the whole list appears again.
Here is the code:
import React, { useState, useEffect } from 'react';
function App() {
const [posts, setPosts] = useState([]);
const [showList, setShowList] = useState(true);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(data => setPosts(data));
}, []);
const onClickHandler = (id) => {
setShowList(false);
}
return (
<div>
{showList ? (
<>
<h1>List of posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<a href="" onClick={() => onClickHandler(post.id)}>
{post.title}
</a>
</li>
))}
</ul>
</>
) : (
<h1>Post title</h1>
)}
</div>
);
}
export default App;