Unwanted rerender in React.js

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;

The list disappears and the page gets blank? Or the text “Post title” appears?

I tried this code on two browsers (Brave and Safari) and clicking on a link just rerenders the list.

… I found the error, the href attribute can’t be empty, if I use href="#" it works!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.