Transforming HTML 'img' elements into React components without losing styling: How do I achieve this with html-to-react?

I am seeking guidance regarding the usage of the html-to-react library.

Consider the following html string:

'<div>
   <img src="test.png" style="width: 100px;"/>
   <img src="test2.png" style="margin: 0px 4px;"/>
</div>'

Normally, this would be parsed as shown below:

import {Parser} from 'html-to-react'
const reactElement = Parser.parse(htmlString);

As a result, a React element with a div and 2 nested img elements would be generated.


Is there a way to parse this string in a manner where each img is substituted with a custom Image component while maintaining the original props and attributes of the img (including styles)?

For example, the resulting react element would contain the following children:

<div>
  <Image src="test.png" style={{width: 100}}/>
  <Image src="test2.png" style={{margin: "0px 4px"}}/>
</div>

Your assistance is greatly appreciated! Thank you.

Answer №1

If you want to achieve that, try the steps below:

Utilize a HTML parser like Parser(htmlString, {
  replace: (domNode) => {
    if (domNode.name === "img") {
      return <Image src={domNode.attribs.src} style={{ width: 100 }} />;
    }
  },
});

While this may not fully address your issue, experimenting with this method could lead you to a potential solution.

Answer №2

Give this a shot:

const { Converter } = require('html-to-react');

const htmlString = '<div>
    <img src="example.png" style="width: 100px;"/>
    <img src="example2.png" style="margin: 0px 4px;"/>
</div>'; 

const reactElement = Converter.convertWithInstructions(
    htmlString,() {
        return true;
    },[
        {replaceChildren: true}
    ]
);

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

"Effortlessly rearrange and remove specific elements using jQuery UI's drag-and-drop

Hello everyone, I have designed a simple interface with 3 different "zones". The first zone contains a list of elements that the user possesses, the second zone allows the user to drag and sort these elements, and the third zone enables the user to delete ...

What is the best way to dynamically add a class to the right navigation element in Vue.js when the :class binding only accepts boolean values?

My issue involves implementing a fixed navigation bar with the following structure: <nav class='navigation'> <div :class="{ active: }" @click='scrollTo(".test1")'></div> <div :class=" ...

Navigating with Breadcrumbs in NextJS

Could anyone provide guidance on creating a breadcrumb for my NextJS application? I am interested in using Ant Design, but the example of the component with React Router is not working for me. Any help would be greatly appreciated! ...

Customizing SVGs for Ion Icons Version 5 in a React Application

I have been using ion icons in React by importing them directly into my index.html. While this method has been working well with the icons from ion icons found here, I know that you can also use custom SVGs by specifying an src attribute in the ion-icon ta ...

Changing the content of the initial post in a loop on WordPress

<?php $freeadvice=new WP_Query('category_name=freeadvice&showposts=10'); while($freeadvice->have_posts() ): $freeadvice->the_post(); ?> <li class="event"> <input type="radio" name="tl-group" /> ...

I am having trouble with my jquery.ajax configuration where the async parameter is set to true. The data is not being sent back to

My goal is to save content whenever a button or hyperlink is clicked using jquery.ajax in an Asp.net 3.5 environment. Here is the logic I am following: I use .bind in jquery to attach my custom method(MakeLog) to a button click or hyperlink click. Sinc ...

Handling errors when using react-query's mutateAsync function

Currently, I am delving into learning the react-query library and I am eager to utilize the mutateAsync function within the useMutation API. Below is the snippet of my code: import { useMutation } from "react-query"; const asyncCall = () => { ...

Can test files be placed under the pages directory in a Next.js project?

Currently, I am in the process of writing integration tests for the API routes within a Next.js application. One question that has arisen is whether it would be problematic to place the index.test.ts file under the /pages directory. My preference leans tow ...

Changing the shape of triangles and adjusting the vertices of a react-three-fiber mesh post-render

For my project, I am trying to reimagine an old Unity QuadSphere code using a revised version with @react-three/fiber. I have created a custom class called QuadGeometry that extends from THREE.BufferGeometry to generate vertices and indices. Initially, the ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Transmit HTML message using the "textarea" tag through email

Whenever I try to send the content of my "textarea" via email, it always ends up being sent as a blank message. How can I fix this issue? Below is my PHP code: <?php $input = json_decode(file_get_contents("php://input"), true); $ToEmail = "<a href ...

Understanding requestAnimationFrame and how it helps in achieving a smooth framerate

I stumbled upon this helpful code snippet that calculates the frame rate for an animation I created. Can someone please explain how it works? Check out the code below: <script src="jquery.js"></script> window.countFPS = (function () { var ...

Exploring ways to iterate through an array of objects to extract specific values

Kindly read this information thoroughly before marking it as a duplicate. I currently possess an array of objects as shown below. const filterParams = [ { 'waterfront_type[]': 'Cove' }, { 'area[]': 'Applehead ...

Incorporating external scss files into next.js (react) for seamless loading

Encountering an error when trying to load SaSS files from zeit node_modules\@zeit\next-css\node_modules\mini-css-extract-plugin\dist\index.js:21} = _webpack2.default; ^TypeError: Cannot destructure property `createHash` of &a ...

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

The error message "React Native - __DEV__ is not defined" has been

I am working on a project that involves [email protected]. I recently deleted the node_modules folder and then executed the following commands: npm i react-native upgrade However, I encountered the following error: react-native.js:15 ReferenceErr ...

Encountered error: Unable to locate module - Path 'fs' not found in '/home/bassam/throwaway/chakra-ts/node_modules/dotenv/lib' within newly generated Chakra application

Started by creating the app using yarn create react-app chakra-ts --template @chakra-ui/typescript. Next, added dotenv with yarn add dotenv Inserted the following code block into App.tsx as per the instructions from dotenv documentation: import * as dote ...

Is it possible for a relative div to automatically adjust its height when the height of the inner absolute div increases?

I am working with the following HTML code snippet: <div id="content"> <div id="leftcol"> <p>Lorem Ipsum</p> </div> </div> along with this CSS styling: #content { width: 780px; padding: 10px; position: relative; back ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...