Query Selector Ref in React returns empty NodeList when trying to access children element

I have some content that I dynamically inject onto the DOM using dangerously set inner HTML. When I reference it using a Ref, and query it, the NodeList is always empty, but when I look at the just sidebarContent.current, the NodeList is not empty.

Why does this happen?

import React, { useEffect, useState } from 'react';

const PostSideBar = ({ sidebarContent }) => {
    const [childNodes, setChildNodes] = useState([]);

    useEffect(() => {
        if (sidebarContent.current) {
            const h2Elements = sidebarContent.current.querySelectorAll('h2');
            setChildNodes(h2Elements);
            console.log(h2Elements); // Check the h2 elements
        }
    }, [sidebarContent]);

    return <div>PostSideBar</div>;
};

export default PostSideBar;

conerting text to worshiptools format using javascript

Im trying to use javascript to convert ultimate guitar.com formatting to worshiptools/chordpro as im going to use the javascript code in gdevelop5 to make a webapp for my church to utilise

I tried writing it many ways but its not exactly putting the text inline but my code outputs only

[G]           [D]          [Em]
Amazing grace, how sweet the sound
[G]          [D]           [C]
That saved a wretch like me

i Tried This

function convertUltimateGuitarToWorshipTools(ultimateGuitarText) {
    // Split input text into lines (songs may have multiple lines of chords/lyrics)
    const lines = ultimateGuitarText.split('n');

    const worshipToolsText = lines.map(line => {
        // This pattern finds the chords, which are typically words in uppercase or lowercase
        const chordPattern = /b([A-G][#b]?(m|maj|min|sus|dim|aug)?)b/g;
        
        // Replace each found chord with the WorshipTools format (i.e., [chord] )
        return line.replace(chordPattern, (match, chord) => {
            return `[${chord}]`;
        });
    }).join('n'); // Join the lines back into a single string

    return worshipToolsText;
}

// Example Ultimate Guitar input (with chords above the lyrics)
const ultimateGuitarText = `
G           D          Em
Amazing grace, how sweet the sound
G          D           C
That saved a wretch like me
`;

// Convert the Ultimate Guitar text to WorshipTools format
const worshipToolsText = convertUltimateGuitarToWorshipTools(ultimateGuitarText);

// Output the converted text
console.log(worshipToolsText);

but i need this to be the output

[G]Amazing grac[D]e, how swee[Em]t the sound
[G]That saved [D]a wretch lik[C]e me

Read data from RFID card reader connected to serial port

I am trying to read data from RFID card reader connected to serial port using javascript’s Web Serial API. I was able to connect to my card reader but the data logged doesn’t seem to be from my console logs. How do I capture this data.

Serial port

Here is the code that I am using.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serial Data Reader</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #status {
            font-size: 16px;
        }
        #serial-data {
            font-size: 18px;
            font-weight: bold;
            color: green;
        }
    </style>
</head>
<body>
    <h1>Serial Data from COM Port</h1>
    
    <button id="connectBtn">Connect to Device</button>
    <p id="status">Not connected</p>
    <p id="serial-data">Waiting for data...</p>

    <script>
        let port;
        let reader;
        let writer;
        let inputDone;
        let inputStream;
        let outputStream;

        const statusElement = document.getElementById('status');
        const serialDataElement = document.getElementById('serial-data');
        const connectButton = document.getElementById('connectBtn');

        // Request permission to access the serial device and open it
        async function connectToDevice() {
            try {
                port = await navigator.serial.requestPort(); // Request the user to select a serial port
                console.log("Port selected:", port); // Log port information
                await port.open({ baudRate: 9600 }); // Open the serial port (adjust baud rate if needed)

                // Setup the input and output streams
                inputStream = port.readable;
                outputStream = port.writable;
                inputDone = inputStream.getReader();

                statusElement.textContent = `Connected to ${port.getInfo().usbVendorId}:${port.getInfo().usbProductId}`;

                // Start reading data from the device
                readSerialData();
            } catch (err) {
                console.error('Error accessing serial port:', err);
                statusElement.textContent = 'Error: Could not connect to device';
            }
        }

        // Read data from the serial port
        async function readSerialData() {
            try {
                // Continuously read data from the device
                while (true) {
                    const { value, done } = await inputDone.read(); // Read the data
                    if (done) {
                        console.log("Stream done");
                        break;
                    }
                    
                    // Log the raw data for debugging
                    console.log("Raw data received:", value);

                    // Check if the value is valid, and decode if it's a valid Uint8Array
                    if (value && value.length > 0) {
                        const receivedData = new TextDecoder().decode(value); // Decode the data
                        console.log("Decoded data:", receivedData); // Log the decoded data
                        serialDataElement.textContent = receivedData.trim(); // Show the data in the frontend
                    } else {
                        console.warn("Empty data received");
                    }
                }
            } catch (err) {
                console.error('Error reading from the serial port:', err);
                statusElement.textContent = 'Error: Failed to read data';
            }
        }

        // Set up the button to connect to the device
        connectButton.addEventListener('click', () => {
            statusElement.textContent = 'Connecting to device...';
            connectToDevice();
        });
    </script>
</body>
</html>

The output:

Select port

Data from card reader

The data logged seems to be different from the data I was looking for. When I scan the card the data that is logged in another website is “1256111915”(card number) but in my console it logs as “733994570”.

How to know if remote peer is disconnected when using Cloudflare Calls SFU?

Is there any way to determine if a remote peer is disconnected while using the Cloudflare SFU without a signaling server?

One solution would be implementing a signaling server that sends a heartbeat every 5 seconds. If no response is received, the session could be terminated.

However, since the client’s peer connection is aware of other connections, I assume it should detect the disconnection.

This is what I have tried to check, but to no avail.

 peerConnection.ontrack = (event: RTCTrackEvent) => {
  const checkTrack = setInterval(() => {
    if (event.track.readyState === "ended") {
      console.log(`Track ${event.track.id} is closed with mid ${event.transceiver.mid}`);
      clearInterval(checkTrack);
    }

    if (event.transceiver.currentDirection === 'stopped' || event.transceiver.currentDirection === 'inactive') {
      console.log(`Transceiver ${event.track.id} is closed with mid ${event.transceiver.mid}`);
      clearInterval(checkTrack);
    }
  }, 500);

  event.track.onended = () => {
    console.log(`${event.transceiver.mid} is ended, ${event.track.id}`);
  };

  event.track.onmute = () => {
    console.log(`${event.transceiver.mid} is muted, ${event.track.id}`);
  };
};

auto-hyperlinking a url in text

I have a situation like

<td><a href="http://www.bar.com/">http://www.bar.com</a>http://www.other.com/</td>

And I have a regular expression set up to capture urls

But is there any reliable way to link link up the other URL? I was thinking I could use .innerHTML, but that is going to catch links that are already linked up. And if I just use textContent, find the url and replace it, how can I set this back to the td without wiping out the bar link? I am not looking for a solution to this specific problem, but a general solution for where an element may have a url but also have other element children (that might also contain url text or in their html/hrefs).

I could go node by node, but this is not reliable – the text could be broken up into multiple nodes, or?

I’d like to auto-link up discovered URLs that aren’t already linked, but I can’t think of a reliable way to do this. Does anyone have a solution to this problem?

Illegal return statement when importing class from Node.js

I’m running Node.js from VS Code. I copied the Color class from this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_classes

Here is the color.mjs:

export class Color {
  #values;
  // …
  toString() {
    return this.#values.join(", ");
  }
}

And then, I import this class from app.js:

import { Color } from "./color.mjs";

Here is the error:

Uncaught SyntaxError SyntaxError: Illegal return statement
    at compileSourceTextModule (<node_internals>/internal/modules/esm/utils:338:16)
    at moduleStrategy (<node_internals>/internal/modules/esm/translators:102:18)
    at #translate (<node_internals>/internal/modules/esm/loader:468:12)
    at loadAndTranslate (<node_internals>/internal/modules/esm/loader:515:27)
    --- await ---
    at runEntryPointWithESMLoader (<node_internals>/internal/modules/run_main:138:19)
    at loadESMFromCJS (<node_internals>/internal/modules/cjs/loader:1329:42)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1536:5)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1706:10)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1289:32)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1108:12)
    at traceSync (<node_internals>/diagnostics_channel:322:14)
    at wrapModuleLoad (<node_internals>/internal/modules/cjs/loader:220:24)
    at executeUserEntryPoint (<node_internals>/internal/modules/run_main:170:5)
    at <anonymous> (<node_internals>/internal/main/run_main_module:36:49)
utils:338
No debugger available, can not send 'variables'

Why can’t I import class in app.js? What’s missing in my code? And how to fix?

React Native Dropdown Picker Category

I am a complete beginner and I am building an inventory app in react native. I came across this external library called Dropdown Picker. I managed to make it work but I just want to ask how can I include categories?

For example:

I want to have two dropdowns; one for category selection and one for specific item selection

I can’t seem to comprehend what is said on the docs because it only says to include a parent property to use categories. I want something like when the first drop down (for category) is given a selection the second dropdown (for specific item) will display the category’s children./

Thank you! Have a great day!

    export const items = [
  { label: "Cement", value: "cement", parent: "form_works" },
  { label: "Steel Rebar", value: "steel_rebar", parent: "steel_works"  },
  { label: "Coco Lumber", value: "coco_lumber", parent: "form_works"  },
  { label: "Sand", value: "sand", parent: "masonry_works"  },
  { label: "Gravel", value: "gravel", parent: "masonry_works"  },
  { label: "Plywood", value: "plywood", parent: "form_works"  },
  { label: "Concrete Mix", value: "concrete_mix", parent: "masonry_works"  },
  { label: "Paint", value: "paint", parent: "architectural_works"  },
  { label: "Nails", value: "nails", parent: "form_works"  },
  { label: "Bricks", value: "bricks", parent: "masonry_works"  },
];

[JavaScript]I want to add watermark to photo like this in Vue, is there any code sample or module I could use?

Problem:

  1. I am building an h5 based app.

  2. There is an Application called Zebra that offers good-looking watermark like this.

  3. What is the sample code that I could use to achieve effects like this.

I would like watermark like this one.

Currently there is a problem uploading picture to overflow.

enter image description here

The image link is as below: https://imgur.com/a/Ok9o6hg

I tried to upload the picture here, but failed.

How to use pdfjs FindController to navigate between matches programmatically?

I am using PDF.js to display PDFs in my React project. I have implemented a search bar that allows users to search for text within the PDF. However, I want to add Next and Previous buttons to navigate between search results and bring the matched text into view.

Here’s what I have so far:

  1. I am using PDFFindController for text search.
  2. I have a search function that highlights all matches.
  3. I added navigation buttons but don’t know how to trigger movement
    between results.

Here’s the relevant code:

eventBus.dispatch('find', {
  query: searchTerm,
  caseSensitive: false,
  highlightAll: true,
  findPrevious: false,
});

And for navigating between matches, I tried:

eventBus.dispatch('again', {
  query: searchTerm,
  caseSensitive: false,
  highlightAll: true,
  findPrevious: false, // or false for next match
});

But this doesn’t work as expected. How can I properly navigate through search results and ensure that the matched text is scrolled into view in PDF.js?

Any guidance or examples would be really helpful! Into View. is there a way to do it.

How to make Material UI sidebar slide and push?

I created a React app that uses a sidebar that is supposed to ease-in-out, but it doesn’t. It just pops in while successfully pushing the content to the right, and pops out when clicked again.

The code uses

  transition: transform 0.3s ease-in-out; 
  transform: translateX(-250px);

to move the sidebar on and off canvas. But it doesn’t seem to be working in the sandbox example. It does work in my real app, but not animated.

Here’s a pic that shows expanded

enter image description here

This one shows it collapsed:

enter image description here

Notice that the sidebar is all white. I can’t get it to be a different color.

I’ve looked at many other examples but they all have issues that I don’t like. I want the button to remain in place when the tray below it slides in and out. Most examples push the header over too, which requires you to move the mouse over to a different spot to close it.

I’d also like the user to have the option of having the sidebar close after selection, or remain open.

I’ve created a small sandbox example. I ported a snipped from the main app, but now the content goes under the menu instead of to the right of it. I hope one of you experts can show me what I’m missing!

Why does this react-bootstrap DropdownButton menu not properly load only on the first click?

I’m working on the Snow Today code repository over at https://nsidc.org/snow-today/snow-viewer and have run into a very confusing and frustrating bug.

When you load the map by clicking “Western United States” and click the “Select A Region” button, the dropdown menu does not initially load unless the button is clicked two more times, or you scroll on the page a little.

On the backend, the button is a react-bootstrap DropdownButton, but the weird part is that the rest of the buttons are also DropdownButtons, but do not experience this issue.

Does anyone have any insight to go about fixing this problem?

can not make a multi form post request via JS run without error

  1. First Question

I have a route tested in insomnia which is working
The route is sent aswith multiform option
also, I have to setchange the preferences in insomnia not to validate SSL

However, I can not make it work on JS

import FormData from 'form-data';
import fetch    from 'node-fetch';
import  https   from 'https';

// process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

const form = new FormData();
form.append("...", "...");
form.append("...", "...");
form.append("...", "...");
form.append("...", "...");

// Following block is to bypass wht authorization
const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001',
    // 'User-Agent': 'insomnia/2023.5.8',
    'agent': httpsAgent,  // This Line is to bypass wht authorization
  }
};

options.body = form;

fetch('https:XXXXX', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

If I dont add form-data, I can not make a multiform option
If I dont add httpAgent, I can not avoid SSL from been verified.
Still, the request sends an error in token.

What am I doing wrong?
How to bypass ALL this requirements

  1. Second Question
    As I said before, I have this route running properly under insomnia
    How can I make to invoke a specific request (from outside INSOMNIA) and make it execute every XXX seconds? Can this be done automatically?

TIA

Smooth OverlayScrollbars scroll from fixed header wheel event in React

I’m building a React application using TypeScript and overlayscrollbars-react to handle scrolling for the main content area. Above this scrollable content, I have a fixed header component (HeaderApp).

Goal:

I want the user to be able to scroll the OverlayScrollbars container even when their mouse cursor is hovering over the fixed HeaderApp. The desired scrolling behavior should be smooth, ideally matching the native feel of scrolling directly within the OverlayScrollbars viewport.

Problem:

Naturally, wheel events over the fixed header don’t scroll the underlying content. Following recommendations (like in OverlayScrollbars GitHub Issue #150), I’m capturing the wheel event on the HeaderApp, preventing its default action, and then programmatically scrolling the OverlayScrollbars container.

However, achieving smooth scrolling comparable to the native OverlayScrollbars behavior has proven difficult.

What I’ve Tried:

  1. Manual Animation with requestAnimationFrame: This approach feels the
    closest, but it’s still not perfect – the scrolling can feel
    slightly jerky or disconnected from the native scroll feel,
    especially with small, single wheel movements.

Here’s the relevant code from my HeaderApp.tsx component:

// Simplified HeaderApp component structure
import React, { useRef, useEffect, useCallback } from 'react';
import type { OverlayScrollbars } from 'overlayscrollbars';
// osGlobalInstance is obtained from the ScrollableContainer component
import { osGlobalInstance } from "../ScrollableContainer/ScrollableContainer";

const HeaderApp: React.FC<HeaderAppProps> = (/*...props*/) => {
const headerRef = useRef<HTMLDivElement>(null);

// Function for smooth scroll animation
const scrollContent = useCallback((deltaY: number) => {
    if (osGlobalInstance) {
        const { scrollOffsetElement } = osGlobalInstance.elements();
        if (!scrollOffsetElement) return;

        // Cancel any previous animation frame for this specific scroll action
        // (Requires managing animation frame IDs - simplified here)
        // cancelAnimationFrame(animationFrameIdRef.current);

        const targetScrollTop = scrollOffsetElement.scrollTop + deltaY;
        const duration = 300; // Animation duration
        const start = scrollOffsetElement.scrollTop;
        const startTime = performance.now();

        const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);

        const smoothScrollStep = (currentTime: number) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const easing = easeOutCubic(progress);

            scrollOffsetElement.scrollTop = start + (targetScrollTop - start) * easing;

            if (progress < 1) {
               requestAnimationFrame(smoothScrollStep);
               // Store animationFrameIdRef.current = requestAnimationFrame(...)
            }
        };

        requestAnimationFrame(smoothScrollStep);
         // Store animationFrameIdRef.current = requestAnimationFrame(...)
    }
 }, []); // Dependency on osGlobalInstance if it changes

 // Wheel event handler on the header
 const handleWheel = useCallback((event: WheelEvent) => {
    if (osGlobalInstance) {
        // Prevent default page scroll and stop propagation
        if (event.cancelable) {
            event.preventDefault();
        }
        event.stopPropagation(); // Prevent event from bubbling further if needed

        // Adjust sensitivity if necessary
        const scrollAmount = event.deltaY * 1.5; // Example multiplier

        scrollContent(scrollAmount);
    }
 }, [scrollContent]); // Dependency on scrollContent

 // Attach wheel listener
 useEffect(() => {
    const headerElement = headerRef.current;
    if (headerElement && osGlobalInstance) {
        headerElement.addEventListener('wheel', handleWheel, { passive: false });
    }
    return () => {
        if (headerElement) {
            headerElement.removeEventListener('wheel', handleWheel);
        }
    };
 }, [osGlobalInstance, handleWheel]); // Dependencies

 return (
    <motion.header ref={headerRef} /* ...other props */ >
        {/* Header content */}
    </motion.header>
 );
};

export default HeaderApp;

// In ScrollableContainer.tsx (simplified):
// export let osGlobalInstance: OverlayScrollbars | null = null;
// ...
// const handleInitialized = (instance: OverlayScrollbars) => {
//     osGlobalInstance = instance;
//     // ...
// };
// ...
// <OverlayScrollbarsComponent events={{ initialized: handleInitialized }} ... >
  1. Using scrollOffsetElement.scrollBy({ behavior: ‘smooth’ }): This
    seemed promising, but calling it rapidly from the stream of wheel
    events caused the browser’s smooth scroll animation to stutter and
    interrupt itself, resulting in very jerky movement. Throttling the
    calls helped slightly but didn’t fully resolve the jerkiness.

  2. Using scrollOffsetElement.scrollBy({ behavior: ‘auto’ }) (with
    Throttling): This avoids the animation interruption issue, but the
    resulting scroll is instantaneous for each step, lacking the desired
    smoothness.

Question:

How can I achieve a truly smooth, native-feeling programmatic scroll of an OverlayScrollbars container triggered by wheel events on a separate fixed element (like a header) in React?

Is there a better way to implement the requestAnimationFrame loop to handle the stream of deltaY values more gracefully? (e.g., adjusting target dynamically, better cancellation).

Is there an OverlayScrollbars API feature or specific technique I’m missing for this scenario?

What is the best practice for translating high-frequency wheel events into a smooth scroll animation within a custom scroll container like OverlayScrollbars?

Any help or pointers would be greatly appreciated!

How do I stream non-critical data?

I have a CSR app with the following route definitions:

const router = createBrowserRouter([
  {
    path: '/app/',
    element: <NavBar />,
    loader: navBarLoader,
    children: [
      {
        path: 'placement-selection',
        Component: PlacementSelection,
        loader: placementSelectionLoader,
        children: [
          {
            path: 'options',
            Component: PlacementSelectionOptions,
            loader: placementSelectionOptionsLoader,
            children: [
              {
                path: 'summary',
                Component: PlacementSelectionOptionsSummary,
                loader: placementSelectionOptionsSummaryLoader,
              },
            ],
          },
        ],
      },
    ],
  },
]);

And the following loaders:

export async function navBarLoader() {
  console.log('called navBarLoader')
  return await new Promise((res, rej) => {
    setTimeout(() => res('response'), 2000)
  })
}

export async function placementSelectionLoader() {
  console.log('called placementSelectionLoader')
  return await new Promise((res, rej) => {
    setTimeout(() => res('response'), 2000)
   })
}

export async function placementSelectionOptionsLoader() {
  console.log('called placementSelectionOptionsLoader')
  return await new Promise((res, rej) => {
    setTimeout(() => res('response'), 2000)
  })
}

export async function placementSelectionOptionsSummaryLoader() {
  console.log('called placementSelectionOptionsSummaryLoader')
  return new Promise((res, rej) => {
    setTimeout(() => res('response'), 10000)
  })
}

This is how PlacementSelectionOptionsSummary is using the loader data:

import { Suspense } from 'react';
import './styles.css';
import { Await } from 'react-router';

export default function PlacementSelectionOptionsSummary({ loaderData }) {
  return (
    <>
      <Suspense fallback={<div>Loading...</div>}>
        <Await resolve={loaderData}>
          {value => <h3>Non critical value: {value}</h3>}
        </Await>
      </Suspense>
      <div className="main-container" style={{ width: '30%' }}>
        <div className="container" style={{ height: '500px' }}>
          <div className="card" style={{ backgroundColor: 'blue' }}>
            <span className="description">
              {' '}
              'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean
              tempor ante ligula, id aliquet ligula laoreet id. In aliquam
              hendrerit mauris, at sagittis tortor efficitur non. Proin egestas
              facilisis augue. Sed aliquet maximus tempus. Nullam ornare
              efficitur blandit. Sed eu mattis tortor. Lorem ipsum dolor sit
              amet, consectetur adipiscing elit. Aenean tempor ante ligula, id
              aliquet ligula laoreet id. In aliquam hendrerit mauris, at
              sagittis tortor efficitur non. Proin egestas facilisis augue. Sed
              aliquet maximus tempus. Nullam ornare efficitur blandit. Sed eu
              mattis tortor',
            </span>
          </div>
        </div>
      </div>
    </>
  );
}

As you can see, placementSelectionOptionsSummaryLoader takes 10 seconds, where all others take 2 seconds.

Based on what’s mentioned here: https://reactrouter.com/how-to/suspense, I figured that all I need to do was to just return the Promise directly, which I am doing for this loader.

Still, the UI for the route /app/placement-selection/options/summary waits for all of these loaders to “finish” before the UI renders.

How can I get most of the UI to render, and then only have PlacementSelectionOptionsSummary render a fallback until it’s slow-10-seconds-loader finishes?