How prevent scrolling to the top of a page on mobile when call is make with react-infinite-scroll-component?

I have an issue with react-infinite-scroll-component…
When i’m at the to bottom of the infinite div, another call is make and the datas is added.
It’s work very well on desktop. But on mobile, the div scroll to the top of page at each render

See my code below:

import { useEffect, useState, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import { setBanner } from "../../redux/filters";

import WindowDimensions from "../utils/WindowDimensions";
import Button from "../utils/Button";
import CarCard from "../utils/Card/CarCard";
import StoperCard from './StoperCard';
import DropDown from "../utils/DropDown";


import { stopers } from "./Stopers";

import Link from "next/link";

import InfiniteScroll from 'react-infinite-scroll-component';
import useApi from "../../api/useApi";

import { useRouter } from "next/router";

import CarNotFound from "../../public/images/catalogue/carnotfound.svg"



function Cars({ sortCars, countCars, query, setQuery, getCars, moreCars, setMoreCars, filtersChanged, removeFilters }) {
    const ref = useRef(null);

    const windowDimension = WindowDimensions();
    
    // Pagination 
    const pageCars = () => {

        if (sortCars.length < countCars) {
            if (window.location.pathname !== undefined && window.location.pathname === '/catalogue') {
                // SET NEW QUERY
                const getQuery = { ...query };
                getQuery.page += 1;
                setQuery(getQuery)
                
    
                // GET CARS
                getCars(getQuery, "infinite-scroll")
            }
        } else {
            setMoreCars(false)
        }
    }


    return (
        <>

                <div className="sm:ml-auto flex flex-col sm:flex-row sm:items-center sm:mt-4 lg:mt-auto">
                    <p className="mr-4 w-fit h-fit mb-4 sm:mb-0 sm:w-max uppercase bg-slate-200 px-4 py-1 min-w-fit rounded-full text-center text-black text-sm">
                        <span className="font-[Gibson-SemiBold] text-xl mr-1">{countCars}</span> résultats
                    </p>
                    <div className="flex flex-wrap sm:flex-nowrap items-center">
                        <p className="w-max uppercase font-[Gibson-SemiBold] mr-4">Tri :</p>
                        <DropDown getList={list_sort} sort={sort} />
                    </div>
                </div>

            </div> 
            <div ref={ref} className="mb-8 px-3 md:pr-8 md:pl-8 mt-6 lg:mt-24 lg:pl-0 lg:pr-12" id='test-zone'>
            {/* <div className="mb-8 md:pr-8 lg:pr-0 md:pl-8 mt-24 lg:pl-0"> */}

                <div id="cars">

                    {/* <div className="border border-primary rounded-lg py-4 px-4 flex items-center bg-gradient">
                        <div className="mr-4"><Exclamation /></div>
                        <p className="uppercase text-sm font-[Gibson-SemiBold] mr-4">Une mise à jour des prix est en cours</p>
                        <div className="-mt-2"><LittleCar /></div>
                    </div> */}
                </div>



                <InfiniteScroll
                    id="car-catalogue"
                    pageStart={0}
                    dataLength={listCars.length} //This is important field to render the next data
                    next={pageCars}
                    hasMore={moreCars}
                    loader={<svg role="status" className="mx-auto mr-2 w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor" />
                        <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill" />
                    </svg>}
                    endMessage={listCars.length === 0 &&
                        <div className="col-span-full pt-4">
                            <div className="w-4/12 mx-auto fill-primary">
                                <CarNotFound />
                            </div>
                            <p className="text-center text-xl mt-4">Aucune voiture ne correspond à votre recherche.</p>
                        </div>
                    }
                    initialScrollY={145}
                    className="relative car-catalogue pb-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-x-5 gap-y-10 auto-cols-fr overflow-hidden h-fit md:pr-8 md:pl-8 lg:pl-0 lg:pr-12"
                    scrollThreshold={0.7}
                >
                    {listCars && listCars.length > 0 && listCars.map((e, i) => (
                        e.type === undefined ?
                        <Link href={`/product/${e.slug}`} key={e._id}>
                                <a>
                                    <div className="h-full">
                                        <CarCard e={e} bgImage={e.bgImage} />
                                    </div>
                                </a>
                            </Link>
                            :
                            <StoperCard element={e} key={i} />
                    )
                    )}

                </InfiniteScroll>

            </div>
        </>
    )

}

export default Cars;


I tried to set the srcollTop position manually but it dont works…

How to sort a list using vue on-click and add an arrow in column using v-bind?

I want the data is sorted in ascending/descending order when I click the corresponding column. Also, I need an arrow after the column to represent the order. I’m stuck in using vue on-click build a function to sort a list and using v-bind to add an arrow. What should I do with my vue/css/html??
Here is my html

    <div id="app">
      <table>
        <thead>
          <tr></tr>
            <th v-for="(header, key) in column" :key="key" v-on:click="sort(header)" v-bind:class="[sortBy === header ? sortDirection : '']">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in rows" :key="row.id">
            <td>{{ row.id }}</td>
            <td>{{ row.name }}</td>
            <td>{{ row.phone }}</td>
          </tr>
        </tbody>
      </table>
    </div>

and my js

var app = new Vue({
  sortBy: "ID",
  sortDirection: "asc",
  el: "#app",
  data: {
    arrow: {
      active: true,
      "text-danger": false,
    },
    column: {
      id: "ID",
      name: "Full Name",
      phone: "Phone",
    },
    rows: [],
  },
  methods: {
    async fetchData() {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const finalRes = await response.json();
      this.rows = finalRes;
    },
    sort(s) {
      if (this.s == this.sortBy) {
        this.sortDirection = this.sortDirection === "asc" ? "desc" : "asc";
      }
      this.sortBy = s;
    },
  },
  computed: {
    sortedProductions: function () {
      return this.products.sort((p1, p2) => {
        let modifier = 1;
        if (this.sortDirection === "desc") modifier = -1;
        if (p1[this.sortBy] < p2[this.sortBy]) return -1 * modifier;
        if (p1[this.sortBy] > p2[this.sortBy]) return 1 * modifier;
        return 0;
      });
    },
  },
  mounted() {
    this.fetchData();
    this.sort();
    this.sortedProductions();
  },
});

My expected outcome:
enter image description here

Its basically a mongoose code problem if anyone of u can help then pls

enter image description here

Error i am getting- DeprecationWarning: Mongoose: the strictQuery option will be switched back to false by default in Mongoose 7. Use mongoose.set('strictQuery', false); if you want to prepare for this change. Or use mongoose.set('strictQuery', true); to suppress this warning.

actually in the useNewUrlParser:true in the 8th line i was trying to figure out the changes that can be made but was unable to solve it.

Getting Undefined using Props with Map function, how can it be resolved?

I’m trying to integrate Mapbox to a tutorial page I’m working on using following code ang calling API:https://www.jsonkeeper.com/b/5NPS, however instead of getting Object values I’m getting “undefined “

AirBnbMap.js (component)

import { useState } from "react";
import Map from "react-map-gl";
import { getCenter } from "geolib";

function AirBnbMap({ searchResults }) {
  //Transform the search results objects in to
  //{ latitude: 52.516272, longitude: 13.377722 },
  //object

  const coordinates = searchResults.map((result) => ({
    longitude: result.long,
    latitude: result.lat,
  }));

  console.log(coordinates);

  //The latitude and longitude of the center of locations coordinates

  const center = getCenter(coordinates);

  const [viewState, setViewState] = useState({
    longitude: center.longitude,
    latitude: center.latitude,
    zoom: 3.5,
  });

  return (
    <Map
      {...viewState}
      onMove={(evt) => setViewState(evt.viewState)}
      style={{ width: "100%", height: "100%" }}
      mapStyle="mapbox://styles/mapbox/streets-v9"
      mapboxAccessToken={process.env.mapbox_key}
    />
  );
}
export default AirBnbMap;

search.js (page)

import { useRouter } from "next/router";
import { format } from "date-fns";
import Header from "../components/Header";
import Footer from "../components/Footer";
import InfoCard from "../components/InfoCard";
import AirBnbMap from "../components/AirBnbMap";

function Search({ searchResults }) {
  const router = useRouter();

  //ES6 Destrucuring
  const { location, startDate, endDate, noOfGuests } = router.query;

  const formattedStartDate = format(new Date(startDate), "dd MMMM yy");
  const formattedEndDate = format(new Date(endDate), "dd MMMM yy");
  const range = `${formattedStartDate} - ${formattedEndDate}`;

  return (
    <div>
      <Header placeholder={`${location} | ${range} | ${noOfGuests} guests`} />
      <main className="flex ">
        <section className="flex-grow pt-14 px-6">
          <p className="text-xs">
            300+ Stays - {range} - for {noOfGuests} guests
          </p>
          <h1 className="text-3xl font-semibold mt-2 mb-6">
            Stays in {location}
          </h1>

          <div className="hidden lg:inline-flex mb-5 space-x-3 text-gray-800 whitespace-nowrap">
            <p className="button">Cancellation Flexibility</p>
            <p className="button">Type of Place</p>
            <p className="button">Price</p>
            <p className="button">Rooms and Beds</p>
            <p className="button">More filters</p>
          </div>

          <div className="flex flex-col">
            {searchResults?.map(
              ({ img, location, title, description, star, price, total }) => (
                <InfoCard
                  key={img}
                  img={img}
                  location={location}
                  title={title}
                  description={description}
                  star={star}
                  price={price}
                  total={total}
                />
              )
            )}
          </div>
        </section>

        <section className="hidden xl:inline-flex xl:min-w-[40%] sticky top-[76px] h-[calc(100vh-76px)]">
          <AirBnbMap />
        </section>
      </main>

      <Footer />
    </div>
  );
}

export default Search;

export async function getServerSideProps() {
  const searchResults = await fetch("https://www.jsonkeeper.com/b/5NPS").then(
    (res) => res.json()
  );

  return {
    props: {
      searchResults,
    },
  };
}

Getting error:
Server Error
TypeError: Cannot read properties of undefined (reading ‘map’)

enter image description here

However expecting Object value:
enter image description here

Html2Canvas save file to the server

I’m using html2canvas to create an image and put it into “#output’ element and that works as intended, but I would also like to save that image on my server but that I can’t get to work.

Here is how I’m trying to do that:

// HTML2Canvas script
function convert() {
  $("#output").empty();
  const original = document.querySelector('#input')
  const canvasContainer = document.querySelector('#output')

  html2canvas(original, {
    scale: 2,
    useCORS: true,
    onrendered: function(canvas) {        
      var imgData = canvas.toDataURL('image/jpeg');   


      var url = '/files/export.php';

      $.ajax({ 
        type: "POST", 
        url: url,
        dataType: 'text',
        data: {
          base64data : imgData
        }
      });     
    }
  }).then(canvas => {
    canvasContainer.appendChild(canvas)
  })
}

And here is my export.php

<?php

    $data = $_REQUEST['base64data']; 
    //echo $data;

    $image = explode('base64,',$data); 


    file_put_contents('here.png', base64_decode($image[1]));

?>

Any clues on what I’m missing here?

Parsing Childnode values in javascript

I have an XML

<root><example><examplevalue>exampletext</examplevalue><examplevalue>exampletext2</examplevalue</example></root>

and I have the following javscript code

            if (window.DOMParser){ // Standard browsers
                var parser = new DOMParser();
                xmlDoc = parser.parseFromString(xmlString, "text/xml");
            }
            else { // Internet Explorer
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(xmlString); 
            }
            var coll=xmlDoc.getElementsByTagName("example");
            console.log(coll[0].childNodes[0].nodeValue);

The console output is

null

I would expect it to be

exampletext

Why are the childnodes not parsed correctly?
childNodes seems to be a method of class node. But the getElementByName return a HTMLCollection object. How does that work?
Thanks for any hints.

webpack devServer Hot reload / HMR reloading but not compiling VueJS components

Using webpack dev server on a vuejs project, when I edit a file the web page is reloaded but not updated.

When sniffing the websocket communication between the client and webpack server I can see this after editing LoginComponent.vue:

enter image description here

The “type”: “static-changed” makes me believe that webpack doesn’t know that it has to compile .vue files on change, and I have no idea how to fix that.

Here is my vue.config.js:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    optimization: {
      runtimeChunk: 'single',
    },
  },
  devServer: {
    client: {
      progress: true,
    },
    static: {
      directory:'/dontmanagestaticfiles'
    },
    port: 80,
    allowedHosts: 'all',
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    
    // hot: true,
    liveReload: true,

    watchFiles: {
      paths: ['src/**'],
      options: {
        // ignored: ['nodes_modules'],
        usePolling: true,
        aggregateTimeout: 300,
        interval: 500,
      }
    },
  },
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          isCustomElement: tag => tag.startsWith('ion-')
        };
        return options;
      });
  }
})

How to start deployed Angular application locally

I have deployed Angular frontend, on server it working fine, there are 3 script

/runtime.0fad6a04e0afb2fa.js    
/polyfills.24f3ec2108a8e0ab.js    
/main.a9b28b9970fe807a.js    

I want to start this application in Firefox, without IIS or Apache – by simple click to Html-page. Is it possible?

But Firefox said me

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///runtime.0fad6a04e0afb2fa.js. (Reason: CORS request not http). 

Is it possible to remove this restriction? Or Firefox never allow me loading and working this scripts?

Vue Slick Carousel

I have slider with VueSlickCarousel.

I want to be able to manually change the pagination during the scrolling, not after it.

  data() {
    return {
      sliderConfig: {
        arrows: false,
        dots: true,
        infinite: true,
        slidesToShow: 2,
        slidesToScroll: 1,
        responsive: [
          {
            breakpoint: 1023,
            settings: {
              slidesToShow: 1,
              slidesToScroll: 1,
            }
          },
        ],
        autoplay: true,
        autoplaySpeed: 2000,
        speed: 6000,
        cssEase: 'ease',
      }
    }
  }

e.stopPropagation() on click event

Please tell me why the e.stopPropagation() function does not work?

$(document).on("click", ".el", function(e) {
  e.stopPropagation();
  alert(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="el" onclick="alert(1)";>Click</div>

Close-On-Click-Away not working when MUI custom field is inside component

In my React component I have a sidebar menu, CustomizeComponentSidebar that in turn contains several other custom html tags. One of them is MUI’s Multiple Select. I made a close-on-click-outside functionality for using useRef. Everything is fine except if I click on MUI’s Multiple Select field, it traces the click as outside the component and closes it. I also tried using MUI’s ClickAwayListener instead, with the same result. Any help appreciated

    const handleClickOutside = (event) =>
    ref.current && !ref.current.contains(event.target) && resetSidebar();

useEffect(
    () => {
        document.addEventListener("click", handleClickOutside, true);

        return () => document
            .removeEventListener("click", handleClickOutside, true);
    },
    [customizeComponentMenu.open]
);

……..

                    <div ref={ ref } className="position-absolute">
                        <CustomizeComponentSidebar
                            props={ props }
                    />
                   </div>

///SelectField looks like this

    return (
    <div>
        <FormControl sx={ { m: 1, width: 300 } }>
            <InputLabel id="demo-multiple-name-label">Select</InputLabel>
            <Select
                labelId="demo-multiple-name-label"
                id="demo-multiple-name"
                multiple={ props.configuration.multipleOptions }
                value={ getValue() }
                onChange={ handleChange }
                input={ <OutlinedInput label="Option" /> }
                MenuProps={ MenuProps }
            >
                { options.map((option) => 
                    (
                        <MenuItem
                            key={ option }
                            value={ option }
                            style={ getStyles(option, optionName, theme) }
                        >
                            { option }
                        </MenuItem>
                    ))
                }
            </Select>
        </FormControl>
    </div>
);

};

export default SelectField;