Tips for incorporating a dynamic element into a specific HTML node that has been retrieved from a React ref

When using React, I am able to access an element using the ref callback once it is rendered on the browser. If the child element exceeds the parent element, the content needs to be manually parsed as it comes from an API call and is not parsed by React.

Note - Currently, I am accessing the element via a react ref callback and attempting to modify it using plain JavaScript. Will this affect the component re-rendering in React? If yes, how can we handle it in React? Or is it okay to modify the DOM directly using plain JavaScript?

(function (e) {
            // How to add an icon at the end of the image if the size of the image exceeds the container            
         }})(window,document)
         
    const parent = element.getBoundingClientRect();
    const imgTags = element.querySelectorAll("img");
    imgTags.forEach(imgTag => {
      const imgBoundingRect = imgTag.getBoundingClientRect();
      if (imgBoundingRect.width > parent.width) {
        const parent = imgTag.parentNode;
        const wrapper = document.createElement('div');
        wrapper.classList.add(styles.horizontalScroll);
        parent.replaceChild(wrapper, imgTag);
        wrapper.appendChild(imgTag);
      }
    });
.horizontalScroll {
  overflow-x: auto;
}

    But I am unsure how to replace the scrollbar with an icon that when clicked, moves instead of scrolling.

Looking for output like this https://i.sstatic.net/03YFt.png

When the image is loaded, and its width exceeds the parent's width, I want to dynamically create nodes using Plain JS. I have managed to capture the width and add overflow, but I'm unsure how to add a button to the node with styling.

Update : React code snippet for getting the Ref

  <div dangerouslySetInnerHTML={createMarkup(myContent)} // This is a set of <p> tags which may or may not contain images inside them coming from the server. Sometimes these images move out of view due to lack of attached style props.
       className={classNames(styles.data, externalStyle)}
       ref={(input) => {
         if (input) {
           myJSFunction(input); // this is the Input
         }
       }}
       /> 

Answer №1

Implementing a dynamic element in React context can be achieved by trying something like the following approach:

export const overFlowIcon = (element) => {
  const oldId = element.querySelectorAll(‘#myID’); // add someId inside to icon and check may Be in case content re renders in React 
    setTimeout(() => {
      const pDiv = element.getBoundingClientRect();
      const imgTags = element.querySelectorAll("img");
      imgTags.forEach(imgTag => {
        const imdDiv = imgTag.getBoundingClientRect();
        if (imdDiv.width > pDiv.width) {
          const parent = imgTag.parentNode;
          parent.style.width = '100%';
          const cont = document.createElement('div');
          const wrap = document.createElement('div'); 
          cont.classList.add(‘stickycontainer');
          wrap.classList.add(‘horizontalScroll');
          container.appendChild(wrap);
          parent.replaceChild(container, imgTag); 
          wrap.appendChild(imgTag);
          const newE = document.createElement('span'); // creating icon
          newE.onclick = (event) => (element.scrollBy(100, 0); event.stopPropagation();)
          newE.classList.add(‘arrow'); // styling a problem can fix
          wrap.appendChild(newE);
        }
      });
    }, 0);
};
.stickycontainer
  position: relative;
}

.horizontalScroll {
  overflow-x: auto;
  display: flex;
}
.arrow {
  position: absolute;
  left: 80%;
  top: 50%;
  border: solid #000;
  border-width: 0 3px 3px 0;
  display: inline-block;
  padding: 3px;
  cursor: pointer;
  transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
}

To ensure that the element is visible and apply transformations using JS, an id can be added to any element to prevent re-rendering effects. The id can be checked before running the method again or an additional argument can be added to the method.

Update After adding the React Ref, if the content is in string format, you can use DOM parser to convert it to the desired format and back to string. The logic can then be implemented within the React Context itself as shown below:

export const horizontalOverflow = (content) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(content, 'text/html');
  const element=  doc.body;
  if (element) {
    const imgTags = element.querySelectorAll("img");
    imgTags.forEach(imgTag => {
      const parent = imgTag.parentNode;
      const wrapper = document.createElement('span');
      wrapper.classList.add(horizontalscrolling);

      parent.replaceChild(wrapper, imgTag);
      wrapper.appendChild(imgTag);
    });
  }
  return element.outerHTML;
};

You can now utilize this method to create your markup.

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

i18next - issue with plural form accuracy

Hey there, I've been using i18next and everything seems to be running smoothly, except when it comes to plural translations. While plural translations work well for some languages, they seem to be causing issues for others. As an example, Croatian d ...

TypeScript is throwing an error about a missing property, even though it has been defined

Within the PianoMK1Props component, there is a prop known as recording which accepts an object with specific properties. The structure of this object is defined like so(the state variable): const [recording, setRecording] = useState({ mode: "REC ...

Angular is throwing an error because it cannot find the definition for

Embarking on a tutorial journey to dive into Angular setup. Facing a persistent error in my code... Error: [$injector:undef] http://errors.angularjs.org/1.6.0/$injector/undef?p0=Bear Listing the order of files within the <head> tag in the html ...

Utilize Z-index to hide elements from view

Encountering an issue with hiding other div elements when one is visible. In the code snippet below, I aim to make Pacific Rim and World War Z disappear using z-index when Star Trek is visible. Here's my HTML code: <!doctype html> <html ...

Initiating a SOAP request to utilize your custom services

Currently, I am in the process of creating a web application that includes providing various web services. After completing the domain model, we are now focusing on implementing both the User Interface (UI) and controller. The controller will consist of t ...

Ways to integrate a React app into an HTML file without using npm start or other similar commands

Hey there! I'm diving into the world of ReactJS and wondering if it's possible to make my react app run directly from the .html file in a browser without needing to call a server. Of course, having a server for other functionalities is fine, but ...

Does JavaScript Map Access Use Indexing for Efficient map.get Retrieval?

Is the map.get method in V8 optimized by indexing JavaScript-Map-object's keys, or does it loop through the entire map to find a key match? I'm curious about the efficiency of map.get with larger mappings containing 500,000+ key/value pairs. I h ...

The latest Bootstrap 5 design elements are incorporated into both FullCalendar version 5 and Angular 8 for a

I recently developed a calendar using FullCalendar v5 in Angular 8, and I was pleased with how it looked without any additional styling. However, I now want to integrate forms for creating events when a date is clicked, so I decided to incorporate Bootstra ...

Issue encountered: The 'secp256k1-browserify' module could not be located when using browserify in conjunction with ethereumjs-lib

Trying to execute a basic script in the browser using the ethereumjs-lib library that has been installed. Utilizing browserify to produce the necessary javascript file for embedding into the html page. However, encountering an error related to missing modu ...

Dynamic extension of classes in SCSSORExtending classes

When working with Vue, I encountered a situation similar to :style="{ [`--chip-bg-hover`]: hoverColorValue, [`--chip-bg-active`]: activeColor, [`--chip-border-hover`]: borderHoverColorValue, }" Then, i ...

Is it better to choose "_this" over "self" in JavaScript?

The Airbnb JavaScript Style Guide recommends using "_this" when saving a reference to the object, as seen in their Style Guide. // bad function() { var self = this; return function() { console.log(self); }; } // bad function() { var that = th ...

Frustrated with the endless page loading caused by three.js

I've been trying to incorporate three.js code to showcase a 3D model in GLTF format, but my webpage keeps getting stuck on pre-loading. I need assistance with displaying a preloading page until all the files are fully loaded. Any help in resolving th ...

Vue.js navigation guards, restrict access to all unauthorized routes, grant entry to specific routes upon successful authentication

I'm currently working on implementing a navigation guard in Vue.js with a specific logic: I want to restrict access to all routes that require authentication and redirect users to the login page if they are not authenticated. The only exception is the ...

The height of the href is not displaying correctly when the text-decoration is disabled and it is placed next to

In my design, I have a link positioned next to an image with perfect vertical alignment. Everything looks great when the text has the standard text-decoration, centered vertically and all that. However, as soon as I remove the text-decoration, leaving the ...

I have come to realize that in my creation, my method does not function flawlessly as

I'm currently experimenting with creating a simple code using vue.js and d3.js. The goal is to plot some charts within the code, so I am attempting to allocate space for the charts by defining a method('add_svg') and executing the method in ...

Using Javascript, access the 'second child' element by referencing the 'first child' element within a shared 'parent element'

// Retrieve the child_2 element using core javascript let parent = document.querySelector('.child_1').closest('.parent'); let child_2 = parent.querySelector('.child_2'); How can I achieve the same functionality as the jQuery ...

Alignment of UI Divs with CSS Bootstrap and HTML

I am facing an issue with two divs in my UI. One div has a label, and the other contains a file selector. Currently, they are stacked vertically instead of being side by side. https://i.stack.imgur.com/fIz03.png How can I align these divs horizontally wit ...

Arrange a stationary child in relation to the grandparent element

I created a small window within a browser window, containing an even smaller window with auto-scrolling text. However, I need some text in the smaller window to remain static and not scroll. Therefore, I used position_fixed which is absolutely related to ...

When implementing the next-translate i18n plugin in Next.js for dynamic routes, there is a limitation where it does not function properly when using a non-default

When using the i18n plugin next-translate in Next.js with dynamic routes, there is an issue with non-default locales. I have set up 2 locales: Arabic "ar" and English "en", with "ar" as the default locale. For instance, when I access this URL: domain.com ...

Utilizing a Jackson-inspired library for handling JSON property names containing dots in Javascript

Is there a way to create a Json with field names that contain dots '.' in a JavaScript application (specifically, TypeScript)? This is the expected Json output: { "tasks.max": "1", "key.converter": "io. ...