Highlight words in markdown content according to search result using Reactjs

I am building React/Django app that is using markdown content I want to put a search bar at which the user can search in the blog content and the words that are matching the search results are highlighted.

I have used react-highlight-words library but I found that It isn’t compatible with markdown content so I am trying using react-string-replace library but there is a problem that faced me in the test

react-string-replace returns array not string so I tried to use a hook (useState) which is an empty string and map each word in the array and append it to the hook then put the Hook inside ReactMarkdown element.

import React from 'react'
import ReactMarkdown from 'react-markdown'
import reactStringReplace from 'react-string-replace';
export default function Mark(){
   
   
    const [stringData, setStringData] = React.useState("");
    
    const content = 'Hey my number is 555-555-5555.';
   const replacearray= reactStringReplace(content, 's', (match, i) => (
        `===${match}===`
      ));
console.log(replacearray)
replacearray.map(word =>{
    console.log(word)
    setStringData(stringData + `${word}`)


})
console.log(stringData)
    return(
       <ReactMarkdown>{stringData}</ReactMarkdown>
    )
}

The result of console.log(replacearray) is:

  Array(3) [ "Hey my number i", "===s===", " 555-555-5555." ]

The result of console.log(word) is:

Hey my number i        mark.js:116:13
===s===                mark.js:116:13
 555-555-5555          mark.js:116:13

The result of console.log(stringData) is:

 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555.

so how the result of stringData is like this although the result of each word is the word itself?

Can’t access the data in socket.io value in react native

I am trying out socket.io for the first time on a React Native application with Node.jsbackend. I am trying to implement messaging system with socket.io, I followed a tutorial, I can see the messages sent when I console.log the returned value from socket.io, but I can’t seem to access it. Like, setting it in a state via useState. Here is the code:

  //connect to socket server
   useEffect(()=>{
    socket.current = io(socket_URL);
    socket.current.on("getMessage", (data)=>{
        console.log(data, 'seocket data')

       setMessages(data)
      
    })
}, [isGetConversationLoading, trigger]);

If I console.log data that came from the socket.current.on, I can see the message I sent, the exact data but it can’t be set as a state. It keeps returning null. What could I be doing wrong?

Colormapping with HSB with faulty output in p5.js

Tried to make a small dynamic grid with a colorpicking function.
Grid is working, colorpicker is showing me a faulty output as it is not displaying a gradient in the gridpoints but rather every second column a proper gradient the column down, though the columns inbetween start in the middle of the column.

I tried changing the mapping variables with no result.


class MyObject {
    constructor (_x, _y,size){
        this.size = {min: 1, max:width/size }
        this.brightness = {min: 0, max: 100}
        this.myX = _x;
        this.myY = _y;
        this.mySize = 3;
        this.myBrightness = 100;
        this.myColor = color(20, 100, 100);
    }


    display (mouseInCanvas) {
        fill(this.myColor);
        noStroke();
        ellipse (this.myX, this.myY, this.mySize, this.mySize);
        if(mouseInCanvas){
            let distance = this.calcualteMouseDistance();
            this.mySize = parseInt(map(distance,  dist(0, 0, width, height),0, this.size.min, this.size.max));
            this.myBrightness = parseInt(map(distance, dist(0, 0, width, height),0, this.brightness.min, this.brightness.max));
            // console.log(this.myBrightness);
        }
        
    }
    
    setColor(newColor){
        this.myColor = color(hue(newColor), saturation(newColor), this.myBrightness);
        console.log(this.myColor);   
    }
    
    calcualteMouseDistance () {
        let distance = dist(mouseX, mouseY, this.myX, this.myY);
        return(distance);
    }

}


// const { color } = require("echarts");

let objects = [];
let size = 40;
let ballcolor;

function setup() {
    createCanvas(800, 800);
    colorMode(HSB, 360, 100, 100, 1);
    for (let x = 0; x < 60; x++) {
        for (let y = 0; y < 60; y++) {
            objects.push(
                new MyObject((width / size) * x, y * (height / size), size)
            );
        }
    }

    ballcolor = color(20, 80, 100);
}

function draw() {
    background(0);
    objects.forEach((obj) => {
        obj.display(mouseincanvas());
        // obj.setColor(ballcolor)
    });
}

function mouseincanvas() {
    return mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height;
}
function mousePressed() {
    for (let index = 0; index < objects.length; index++) {
        const obj = objects[index];
        // obj.setColor(color(map(index%size,0,size,0,360),map(parseInt(index/size),0,size,0,225),100));
        // console.log(map(index%size,0,size,0,360));
        console.log(obj);
        obj.setColor(
            color(
                int(map(index / size, 0, size, 0, 255)),
                map(index % size, 0, size, 0, 255),
                100
            )
        );

        // console.log(map(index%size,0,size,0,100));
    }
}
function mouseReleased() {
    for (let index = 0; index < objects.length; index++) {
        const obj = objects[index];
        obj.setColor(color(int(map(mouseX, 0, width, 0, 360)), 100, 100));
    }
}

Updating an element’s index in an array to zero with a handler function

I want to select an image’s index in an array to be set to zero when it is clicked.

For simplicity sake, I have image 1 (index == 0) and image 2 (index == 1). When I click on image 2, the handleImageClick function works by setting image 2’s index to zero. The problem is that in order to set image 1’s index to zero again, I have to click on image 2 a second time which doesn’t make sense. Why is this logical error occuring?

Here is my handleImageClick function :

   const handleImageClick = (index) => {
      const newImages = [...images];
      const clickedImage = newImages[index];
      newImages.splice(index, 1);
      newImages.unshift(clickedImage);
      setImages(newImages);
    };

Here is how the images are displayed and where onClick is placed:

<Grid templateColumns="repeat(3, 1fr)" gap={4} mt={4}>
          {urls.map((url, index) => (
            <Box 
            className="img-container" 
            key={index} 
            position="relative" 
            onClick={() => handleImageClick(index)}
            
            >
              <Image 
                maxHeight="125px" 
                maxW="180px" 
                src={url} 
              />
              <IconButton
                aria-label="Delete"
                icon={<DeleteIcon />}
                onClick={() => handleDeleteImage(index)}
                size="sm"
                colorScheme="red"
                position="absolute"
                top="5px"
                right="5px"
              />
            </Box>
          ))}
        </Grid>

urls.map is an array of temporary blob urls that allows the user to see previews of their images.

Any help would be appreciated. Thank you.

Function returns only last update of the properties of an object, during a for loop, why?

Why is it when you push a constantly updating object into an array using a for loop, it pushes only the last iteration property values(last updated property values)?

My task was: It is your job to identify every element in an array that isn’t sequential.

You should return the results as an array of objects with two values.

I tried this and it didn’t work as I expected:

function allNonConsecutive(arr) {
  let nonC = {
    i: 0,
    n: 0,
  };
  let arrNonC = [];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] - 1 !== arr[i - 1]) {
      nonC.i = arr.indexOf(arr[i]);
      nonC.n = arr[i];
      arrNonC.push(nonC);
    } else continue;
  }
  return arrNonC;
}
Returns: [{i:7, n:10}, {i:7, n:10}] ❌ 

Although I solved it like this:

function allNonConsecutive(arr) {
  let nonC = {};
  let arrNonC = [];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] - 1 !== arr[i - 1]) {
      nonC = {
        i: arr.indexOf(arr[i]),
        n: arr[i],
      };
      arrNonC.push(nonC);
    } else continue;
  }
  return arrNonC;
}
Returns: [{i:4, n:6}, {i:7, n:10}] ✔️

Filter the objects that have the same field value of the value that we provide

My goal is to show only banners that have the same CODE provided in the KEYS array to filter. So I only want the banners which have the same code contained in the array KEYS. Thanks for the help.

const keys = ['343747', '213747', '123444']
export const banners = [
    {
    id: 1,
    name: 'Cashback',
    code: '343747',
    },
    {
    id: 2,
    name: 'Cosmetic',
    code: '213747',
    },
    {
    id: 3,
    name: 'Jeans',
    code: '123444',
    },
    {
    id: 4,
    name: 'WelcomeBonus',
    code: '54344',
    },
]

Number 4 has a code that is not present in the KEYS array so it shouldn’t be shown.

I tried to use the FILTER, REDUCE or MAP method but I couldn’t get to the solution. Thanks to anyone who can help me.

Why Zero Hour, Minute and Seconds is 8 Hours Ahead?

I’m at West Coast, verified 7 hours behind UTC/GMT. Thought the followings are equivalent

const d =  new Date('2023-01-01'); 
const d2 = new Date('2023-01-01 0:0:0.000'); 

Result:

Sat Dec 31 2022 16:00:00 GMT-0800 (Pacific Standard Time)

Sun Jan 01 2023 00:00:00 GMT-0800 (Pacific Standard Time)

Why are Zero hours, minutes, seconds and milliseconds are ahead? And why it’s not 7 hours diff?

moving hetml item out of screen with javascript

I am compelet begginer in JS and front-end iam working on a website and i have and image in this div :

</nav>
  <div class="container-fluid site-header" id="main-image">
      <div class="image-on-text-container bg-secondary">
          <span class="site-brand"></span>
      </div>
  </div>

with this id : main-image

and i want to when user scroll down image goes left slowly then delet the image this is css of this image :

.site-header {
    background-image: 
url("https://images.pexels.com/photos/2159065/pexels-photo-2159065.jpeg? 
auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200");
    height: 100vh;
    background-repeat: no-repeat;
    background-size: cover;
    justify-content: center;
    position: relative;
}

#main-image {
    position: marker;
    left: 0;
    transition: ease-out;
}

i write this script for this but its movig very bad i want the way to movite it slowler and maybe with some effect but i dont know how i need some guidence please :

var x = 0;
var screenWidth = window.innerWidth;


window.onscroll = function ()
{
    var box = document.getElementById("main-image");

    setInterval(function() {
            if (x<= screenWidth){
                x ++;
                box.style.left = x + "px";
            }
            else {
                box.style.display= "none";
            }


        },10)

How to toggle my Chrome Extension Script off without the user having to refresh to see the changes

Created a chrome extension that alters text on that webpage.
The toggle on switch activates the code and changes the text.(Perfect)

Content.js:

// Listen for messages from the popup
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.toggle) {
      // Toggle the bolding of text on the page
      toggleBold();
    }
  });
  
  // Function to toggle the bolding of text on the page
  function toggleBold() {

MY SCRIPT CODE IS HERE


}

Popup.js

const toggleButton = document.getElementById('toggleButton');

// Send a message to the content.js to turn it on or off
if (toggleButton) {
toggleButton.addEventListener('click', () => {
  chrome.tabs.query({active: true, currentWindow: true}, tabs => {
    const tab = tabs[0];
    chrome.tabs.sendMessage(tab.id, {toggle: true});
    toggleButton.innerText = toggleButton.innerText === 'Turn On' ? 'Turn Off' : 'Turn On';
  });
});
}

Popup.html

<!DOCTYPE html>
<html>
  <head>
    <title>Turn On/Off</title>
    <style>
      button {
        font-size: 16px;
        padding: 10px;
      }
    </style>
  </head>
  <body>
 
    <button id="toggleButton">Turn On</button>
    <script src="popup.js"></script>
  </body>
</html>

When I toggle my extension off it just runs the code again.(Flaw)
Just how my code activates immediately on the page. How can I make the code deactivate immediately without user needing to refresh to see those changes? And how can I make my script stay active while the user navigates to other websites and refreshes?

Thanks in advanced

I am researching pushstate to maybe create an option to undo the script when the user toggles off. But i havent checked yet for an option to keep my script activated when the user navigates and refreshes while toggled on.

Pass onBlur and sx props in slotsProp of MUI DatePicker 6

I have this DatePicker component using MUI DatePicker v6.

/* eslint-disable no-unused-vars */
// @ts-nocheck
import * as React from 'react';
import { Controller } from 'react-hook-form';
import TextField from '@mui/material/TextField';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import './common.css';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
export const CustomDatePicker = (props) => {
  const { control, name, label } = props;
  const [error, setError] = React.useState(null);
  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { onChange, value, ref }, fieldState: { error } }) => (
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <DatePicker
            size="small"
            name={name}
            label={label}
            control={control}
            format="DD-MMM-YYYY"
            value={value}
            onChange={(event) => {
              onChange(event);
            }}
            disableFuture
            sx={{ width: props.width ?? 250 }}
            InputProps={{
              style: {
                padding: 8
              }
            }}
            disableMaskedInput
            slotProps={{
              textField: {
                helperText: error?.message,
                error: error?.message ? true : false,
                size: 'small',
                readOnly: true
                //add sx here
                //add onBlur here
              }
            }}
          />
        </LocalizationProvider>
      )}
    />
  );
};
export default CustomDatePicker;

I want to set an onBlur and sx props on generated TextField component but don’t know the correct format when props are set as JSON object. Cannot find any example in the documentation too.

How can I publish a stream in WHIP protocol

I wanted to find an easy enough way to publish audio and video streams, so I learned about the WHIP protocol, which company currently offers this streaming service?

I tried several schemes, such as Agora and 100ms, but both need to integrate SDKs, and the interface is complex, the business I want to implement is simple, just push and pull streams, and I have the foundation to develop webrtc, but the server side is too complicated to build, so I want to find a company to provide WIP services, so I can use Android, iOS, and web devices to establish streaming links

How to access binary files from flask server packaged w/ Electron app?

I have a packaged electron app that includes a flask server as the “backend”, which I spawn via:

    const execfile = require('node:child_process').execFile;
    const binariesPath = path.resolve(
      path.join(path.dirname(app.getAppPath()), 'app/app')
    );
    execfile(
      binariesPath,
      {
        windowsHide: false,
      },
...

This launches the app located in /app and runs fine. However, I have some additional binaries that I packaged with the electron app that the Flask app needs access to. I packaged the extra files in my package.json like this:

"extraFiles": [
      {
        "from": "src/flask/dist",
        "to": "resources/app/",
        "filter": [
          "**/*"
        ]
      }
    ],

However, from the perspective of my Flask app, I’m not sure how to access these binary files in /app. How do I get the path to them? My intuition is that I can get the app directory via app.getAppPath() in my frontend, and then pass that as an argument in my POST requests but not sure if this is the correct route.