How to remove srcset in the image tag which is migrated from WordPress?

Without removing srcset the code will be as shown below:

<img loading="lazy" decoding="async" width="612" height="173" src="http://jobinandjismi.in/wp-content/uploads/2022/03/image-43.png" alt="" class="wp-image-12981" srcset="https://wp.jjknowledgebase.com/wp-content/uploads/2022/03/image-43.png 612w, https://wp.jjknowledgebase.com/wp-content/uploads/2022/03/image-43-300x85.png 300w, https://wp.jjknowledgebase.com/wp-content/uploads/2022/03/image-43-60x17.png 60w, https://wp.jjknowledgebase.com/wp-content/uploads/2022/03/image-43-150x42.png 150w" sizes="(max-width: 612px) 100vw, 612px">

The image will be as shown below:

The following steps should be taken to fix the:

Step 1: At first, we need to create a component (components/CustomHTMLRenderer.js)

import React, { useMemo } from 'react';

const CustomHTMLRenderer = ({ html }) => {
  const sanitizedHTML = useMemo(() => {
    return html.replace(/<img(.*?)src=["'](.*?)["'](.*?)s*srcset=["'](.*?)["'](.*?)>/g, (match, p1, p2, p3, p4, p5) => {
      console.log('Matched values:', p1, p2, p3, p4, p5);
      const withoutSrcSet = `<img${p1}src="${p2}"${p3}>`;
      return withoutSrcSet;
    });
  }, [html]);
  return <div dangerouslySetInnerHTML={{ __html: sanitizedHTML }} />;
};

export default CustomHTMLRenderer;

Step 2: Import the CustomHTMLRenderer to the pages we need:

import CustomHTMLRenderer from '../../components/CustomHTMLRenderer';

Step 3: Also add the code given below:

 <div className="mt-10 post-main-entryContents"
                dangerouslySetInnerHTML={{ __html: post?.content?.rendered }}
              />

Replace it with the code provided below:

<div className="mt-10 post-main-entryContents">
                <CustomHTMLRenderer html={post?.content?.rendered} />
              </div>

After removing srcset the code will be as shown below:

<img loading="lazy" decoding="async" width="628" height="387" src="http://jobinandjismi.in/wp-content/uploads/2022/03/image-42.png" alt="" class="wp-image-12980">

The image will be as shown below:

Leave a comment

Your email address will not be published. Required fields are marked *