React - Next Blog: Issue with empty lines displaying on the browser

Currently, I am developing a blog that retrieves data from Mongo Atlas. The blog is built using Next.js version 9.5.4 and is hosted on Vercel. The blog page utilizes static props and regeneration.

The data is fetched in JSON format and then stringified for processing.

 return {
      props: {
        articles: JSON.parse(JSON.stringify(articles)),
      },

Each blog post (referred to as articles) consists of a title, text, and a signature line with the author's name and publication date. Some articles include links while others feature one or two pictures. Here is the relevant portion of the code:

{articles.map((article) => (
      <li key={article.id}>
      <h2  className={styles.blogtitle} >{article.title}</h2>
      <p  className={styles.blogtext}>{article.text}</p>
      <img src={article.image1} className={styles.blogimage} alt={article.alt1} ></img>
      <img src={article.image2} className={styles.blogimage} alt={article.alt2} ></img>
      <p>{""}
      <a
       href={article.link} 
      title={article.link}
      target="_blank"
      rel="noopener noreferrer" >
      {article.link}            
      </a>
      </p>
      <p  className={styles.bloginfos}>{article.author}, today at {article.date.slice(0,10)} - {article.date.slice(11,16)} h</p>
      </li>
    ))}

After adding images and links, posts without corresponding content display empty lines for two images and one link. Upon inspection with the browser console, it appears that each list item receives:

<img class="nextGeneratedName1"> <img class="nextGeneratedName1">

however, these elements are empty. Additionally, there is a p tag containing:

<a target="_blank" rel="noopener noreferrer"></a>

This behavior causes undesired empty space in the displayed content. It seems that Next.js automatically adds the image classes even when no content is present. The empty paragraph should not be rendered in HTML since it lacks both content and a specific class. For further reference, the entire project is available on GitHub. You can view the blog.js file here.

Answer №1

To ensure that the image url is displayed only when it is available, you can perform a condition check. For example, in line 30 of your blog.js file, you can do the following:

{article.image1 && <img src={article.image1} className={styles.blogimage} alt={article.alt1}></img>}

You can apply similar logic for other elements like a, p, etc., that may potentially be empty under certain circumstances.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS animation properties

Is it possible to animate only the div container and not the "p" inside? div { width: 100px; height: 100px; background-color: red; -webkit-animation-name: example; /* Safari 4.0 - 8.0 */ -webkit-animation-duration: 4s; /* Safari 4.0 ...

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

JavaScript has encountered a syntax error

When working on an animation in javascript, I encountered a problem that I can't seem to identify. I am attempting to make the pan function work with the "mover" function, but it seems like either I am not using the properties correctly within the "tr ...

Can CSS be used to communicate to JavaScript which media queries are currently in effect?

Is there a way for Javascript to detect when a specific CSS media query is active without repeating the conditions of the media query in Javascript? Perhaps something similar to an HTML data attribute, but for CSS. For example: CSS @media (min-width: 94 ...

Looking to incorporate Functional Components in React using the package "@types/react" version "^18.0.17"? Learn how here!

With the removal of the children prop from React.FC type, what is the new approach for typing components? ...

I'm encountering an issue with VS Code where it is unable to identify ejs tags within my project

I'm running into an issue with Vs code where it's not recognizing ejs output tags when they're inside an html tag, like in the input tag below : <input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form. ...

Discovering the RootState type dynamically within redux toolkit using the makeStore function

I am currently working on obtaining the type of my redux store to define the RootState type. Previously, I was just creating and exporting a store instance following the instructions in the redux toolkit documentation without encountering any issues. Howev ...

Having trouble sending a file from React to Express using axios.post

Despite my best efforts, I can't seem to get this axios.post request working properly in React. I need to pass multiple values, including a PDF file, but it's not coming through correctly on the Express side. The strange thing is, when I console. ...

Steps for changing an image with another image upon button click in Angular 6

I have a button with an image and text. When the button is clicked, I want to change both the image and content. Here's the code I'm currently using: <div class="btn-default"> <button name="Save" [ngClass]="[bntStyle]" (click)="submit ...

Unable to retrieve the correct `this` value within an axios callback

Feeling a bit fuzzy-brained at the moment. I've put together this code that downloads a JSON from a URL and displays it on the screen: export default class App extends React.Component { constructor(props) { super(props); this.state = { data: [], } } ...

Transmitting a custom PDF document through email with React and Node.js

Currently, I am in the process of developing an application designed to streamline the completion of a complex form. The data entered into this form will be stored on a remote database for future reference and editing purposes. Once the form is ready for s ...

The Socket.io socket listener in the Next.js API is failing to refresh and update properly

I am working on a Next.js project that includes a basic implementation of Socket.IO. Check out the code snippet below: // pages/index.tsx let socket: Socket; const Home: NextPage = () => { useEffect(() => { async function initializeSocket() { ...

How can I incorporate a counter into my ng-repeat loop in Angular?

Do you know where I can find documentation on adding a numbered count to each item returned by an ng-repeat in Angular? This is not like assigning an Id, but more like, if 4 items are returned, each JSON object could include a number before the data. Her ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

What is the most efficient method for transferring images to Google Cloud Storage?

Context: I am currently working on incorporating a new feature that allows users to upload their profile image to Google Cloud Storage (GCS). I am aware of two methods for uploading objects using the client library: The conventional method (refer here: h ...

Error: The function concat() is not valid for messagesRef.current

I'm currently developing an app that enables users to interact with AI by asking questions related to the uploaded PDF file. However, I've encountered a problem while interacting with AI on the client side - I keep receiving the error 'TypeE ...

Is there a way to utilize jQuery to determine the distance the user has scrolled down?

Looking for some help with changing the style of an element based on scroll position using jQuery. Specifically, I want to add a class name to a div once the user has scrolled beyond 200 pixels and then remove the class name when they scroll back up to l ...

Is it possible to create a table using a loop in an SQLite query?

Welcome In the company where I work, Excel is currently being used to manage a large database of items for cost estimation purposes. To simplify this process, I am developing an Electron App that will replace Excel with a more user-friendly interface and ...

Retrieve a .js file on the fly instead of using imports

My app is designed to provide support for over 30 languages, and I utilized react-intl for this purpose. However, importing every locale file individually results in unnecessary bloat as each file averages around 7-8kb. I am looking for a way to streamline ...

Incorporating next.js static assets within a docker environment with nginx

My blog application built with next.js is running inside a docker container. The container can be accessed on port 5000. Despite having set assetPrefix:'/blog' in the next.config file, the browser is struggling to load the assets like CSS and JS ...