Nextjs: react-dom.development.js?ac89:14906 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component

This is my code:

<div onClick={(e) => handleClick()}>Join Us</div>

This is handleclick:

const handleClick = () => {
    console.log(Lang.getLocale())
};

And this is my function:

class Lang {
    static getLocale() {
        const { locale } = useRouter();
        return locale?.toString()
    }
}

export default Lang

But I get this error:

react-dom.development.js?ac89:14906 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Hover on a particular dash of a stroke

I would like to create the following rating system using css, html and if needed js :

enter image description here

When the user puts his mouse on a particular dash of the circle stroke it fills all the previous dash with a particular color. For now I have done the following :

* {
  background-color: blue;
}

.progress-ring__circle {
  stroke-dasharray: 25 6;
}
<svg
   class="progress-ring"
   width="120"
   height="120">
  <circle
    class="progress-ring__circle"
    stroke="grey"
    stroke-width="10"
    fill="transparent"
    r="52"
    cx="60"
    cy="60"/>
</svg>

The problem is that I don’t know how to detect on which dash the user has his mouse on. Is there any way to do this using JS or CSS ?

Datepicker is closing in an awkward way

When the date picker is open I want it to be the same width as the associated input text box. When the date picker closes, I want it to close in a single motion. But as soon I select a to and from date, no longer does the datepicker close in a single motion.

I have tried ideas such as inst.dpDiv.outerWidth(0) and partially modifying the code found here https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css. But nothing has worked and now I feel like I am going round round in circles.

I was going to include a JSFiddle but because of discrepancies between running the code in Sublime and JSFiddle I decided not to. And because the problem is only on the screen for a second (or less) I cannot take a screenshot.

I have tried hard to only include relevant code below. Does anyone have any suggestions?

<!DOCTYPE html>
<html lang="en">
<head>

    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    

<script>
    $(function(){
          from = $('#arrivalDate').datepicker({


            beforeShow: function (input, inst) {
                setTimeout(function() {
                    inst.dpDiv.outerWidth($('#arrivalDate').outerWidth());
                },0);
            }, //End of beforeShow: function (input, inst) 



             onClose:function(){

                if($('#arrivalDate').datepicker('getDate') != null)

                     {if($('#departureDate').datepicker('getDate') == null)
                        {jQuery('#departureDate').datepicker('show')};       
                      }
            }  //End of onClose:function(){




          }) // End of from = $('#arrivalDate').datepicker({ 

                .on( "change", function(input, inst) { ///This part goes after from = $('#arrivalDate').datepicker({ xyz })
        
       
                     to.datepicker( "option", "minDate", $( "#arrivalDate").datepicker("getDate"))


            });

    
                to = $('#departureDate').datepicker({
       
                beforeShow: function (input, inst) {
                    setTimeout(function() {
                        inst.dpDiv.outerWidth($('#departureDate').outerWidth());
                    },0);
                }, //End of beforeShow: function (input, inst) 



                 onClose:function(){

                    if($('#departureDate').datepicker('getDate') != null)

                         {if($('#arrivalDate').datepicker('getDate') == null)
                            {jQuery('#arrivalDate').datepicker('show')};       
                          }

                  }  //End of onClose:function(){

          }) // End of from = $('#arrivalDate').datepicker({ 

        .on( "change", ///This part goes after from = $('#arrivalDate').datepicker({ xyz })
                function(input, inst) { 
         
               from.datepicker( 
               "option", "maxDate", $( "#departureDate").datepicker("getDate")
              )

       
                    }

        );
    

         $('div.ui-datepicker').on('click',function(){
         $(this).outerWidth($('#arrivalDate').outerWidth());
         });


  });
</script>


<style>


input {
  width: 50%;
  height: 50px
}





</style>



</head>



<body>
 


 <div class="box">
  <input id="arrivalDate" type="text" />
</div>




 <div class="box">
  <input id="departureDate" type="text" />
</div>



</body>
</html>

Nested Function – this.function in javascript still occur the “is not a function” error

I want to write the two function inside RomanNumerals function

RomanNumerals.toRoman()
RomanNumberals.fromRoman()

which will return the Roman Number or decode the Roman Numerals. The code is the following as below

function RomanNumerals(x){
this.toRoman = function(x){
        var  roman = {M:1000,CM:900, D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1 }
  
  var ans = '';
  while(number>0){
      for(a in roman){ 
          console.log(a,ans)
          if(roman[a]<=number)
          { ans += a; 
            number-=roman[a]; 
            console.log(a,ans,number)
            break;}
              
      }
  }
  return ans;
  }
  
this.fromRoman = function(x){
        let sum = 0, a;
        const romanNo = { I : 1, V : 5, X : 10, L : 50, C: 100, D : 500, M : 1000}
        const numbers = roman.split('')
        for(let i = 0; i < numbers.length; i++ ){
            if (romanNo[numbers[i]] < romanNo[numbers[i+1]])
            {
                sum += romanNo[numbers[i+1]] - romanNo[numbers[i]]
                i++;
            }
            else 
            {
                 sum+=romanNo[numbers[i]]
            }
        }
        return sum

    }

}

but it is still occouring the following error

TypeError: RomanNumerals.toRoman is not a function

I have looked up a few references similar to this post and followed the following link
JavaScript Nested function
the code syntax mentioned at the below

function Fizz(qux)
{
  this.buzz = function(){
    console.log( qux );
  };
}

still occur the following error as well

TypeError: Fizz.buzz is not a function

What am I missing here to solve this issue?

vue/composition-api ref only 1 level deep

I know that with ref you have an object/array/primitive reactive, and if it was an object or array it is made deeply reactive.

And with shallowRef you can have only the variable itself reactive but is not made deeply reactive.

In my case I have an array of JSONs where I would like to make reactive the array and the first deep level, because the only actions I am doing is push/slice new items or change the array variable.

So I could use ref([]), but this will make the full JSON reactive which I don’t need.
And I can not use shallowRef(), because this will work when changing the full json. But won’t work with the push/slice actions.

Is there something I am missing? How can I do this approach?

const arr = shallowRef([]);

arr.value.push(JSON); // Not reactive
arr.value.slice(index, 1); //Not reactive
arr.value = [JSON_1, JSON_2]; //reactive

Transform object in js

I want transform a Javascript object to a different form. Lets take an example.

may be I have an object like this,

[
  {
    "_id": 1,
    "name": "abc",
    "sub": [
      "bbb",
      "ccc"
    ]
  },
  {
    "_id": 1,
    "name": "abc1",
    "sub": [
      "bbb1"
    ]
  },
  {
    "_id": 1,
    "name": "abc"
  }
]

and I want to transform that like below,

[
  {
    "_id": 1,
    "name": "abc",
    "sub": [
      {
        "sub": "bbb"
      },
      {
        "sub": "ccc"
      }
    ]
  },
  {
    "_id": 1,
    "name": "abc1",
    "sub": [
      {
        "sub": "bbb1"
      }
    ]
  },
  {
    "_id": 1,
    "name": "abc"
  }
]

can anyone please help me to solve this. Thanks.

JavaScript, checking an integer’s value

Please help me, I’m new in programming

The webpage is asking for the user’s age. The input value has already been fetched, but you have to fill in the missing code. When the page calls the function checkAge(), first print in the console “The input age: [age]”, followed by one of the following, depending on the value:

18 years or more: “The user is an adult.”

Under 18 years, but over 0 years: “The user is not yet an adult.”

Otherwise: “Invalid input!”

Example output:
Input age: 18
The user is an adult.
The output of the program must be exactly the same as the example output (the most strict comparison level)

My code:

function checkAge() {
  var age = document.getElementById("age").value;
  var age = Number(age);
  if (age >= 18) {
    console.log("The user is an adult.");
  } else if (age > 0 && age < 18) {
    console.log("The user is not yet an adult.");
  } else {
    console.log("Invalid input.");
  }
}

Compiler gives: Incorrect output: your program printed “The”, but should have printed “Input”

Try/catch a promise or just catch?

this.$auth.loginWith returns a promise, but I am unsure if I should wrap it in a try/catch or just use a catch on the promise.

Which is the correct way?

Try/Catch:

async login() {
            try {
                const response = await this.$auth.loginWith('laravelSanctum', {
                    data: {
                        email: 'xxx',
                        password: 'xxx',
                    },
                });

                this.$auth.setUser(response.data.data);
            } catch (e) {

            }
        },

Catch:

async login() {
                const response = await this.$auth.loginWith('laravelSanctum', {
                    data: {
                        email: 'xxx',
                        password: 'xxx',
                    },
                }).catch(function(e) {
                });

                this.$auth.setUser(response.data.data);
        },

How can i remove an table’s tr with javascript?

first of all, super beginner here. I’m trying to do a to do list. The add part works fine, it looks like this:

HTML:

<input type="text" id="input">
    <div class="container">
        <button id="salvar">Save</button>
        <button id="remover">Remove</button>
    </div>

    <table id="todoitems">
        <tr>
            <th>Tarefa</th>
        </tr>
    </table>

And here’s the JS:

let salvar = document.getElementById("salvar")
let remove = document.getElementById("remover")


salvar.onclick = saveitem

function saveitem(){
let item = document.getElementById("input").value
let novoitem = document.createElement("tr")
let lista = document.getElementById("todoitems")
novoitem.innerText = item
lista.appendChild(novoitem)


}

How can i create a function that removes the last added item?

RegEx to format phone number

I want to format bellow types into this phone number: +33 (0) 6 60 23 12 47

Types are:

Type-1:

  • 0660231247
  • 06.60.23.12.47
  • 06-60-23-12-47
  • 06/60/23/12/47

    Type-2:

  • 336 60 23 12 47
  • 336 660231247
  • 336 6.60.23.12.47
  • 336 6-60-23-12-47
  • 336 6/60/23/12/47
  • 336 6 60 23 12 47

    Type-3:

  • +336 60 23 12 47
  • +336 660231247
  • +336 6.60.23.12.47
  • +336 6-60-23-12-47
  • +336 6/60/23/12/47
  • +336 6 60 23 12 47

    I use this regex for Type-1 and I need simplier.

console.log((/^((\+|00)33|0) *([1-9])([s-|,|.\/]*[0-9]{2}){1}([s-|,|.\/]*[0-9]{2}){1}([s-|,|.\/]*[0-9]{2}){1}([s-|,|.\/]*[0-9]{2}){1}/).exec('0660231247'));

Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of

I’m using react-leaflet and I added a marker with an event Handler on click to zoom to this marker , but when I try to use const map=useMap() all I get is this error => :

Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

There might be similar questions but none have answers, can anyone please help with this?
This is my code:

const map = useMap()
 return (
        <div>
          <MapContainer
            className="leaflet-container"
            center={[33.8735578, 35.86379]}
            zoom={9}>

            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />

            <Marker
              icon={port}
              eventHandlers={{
                click: (e) => {
                  map.setView(e.latlng, 14);
                },
              }}
              position={[33.90757548098519, 35.51700873340635]}
            ></Marker>
          </MapContainer>

Thanks!

How can I fix the NaN error in Javascipt I keep getting?

I’ve a practical assignment for middle school, to make a simple Javascript website. But I keep getting a NaN on my website. I can’t figure out why. Mayby some-one understands what I do wrong. Thanks by forehand.

<input type="text" id="inputValue">
<p id="answer"></p>

<script>
var timer = setInterval(time,5000);

function time()
{
    document.getElementById('change').innerHTML = Date();
}
var calculate = setInterval(calcFunction, 5000);
function calcFunction(inputValue, change)
{
    var answer = Number(inputValue) + 1;
    document.getElementById('answer').innerHTML = answer;
}
</script>

svg map open box when click but can not close it

cant close the box
the code im using
https://codepen.io/dudleystorey/pen/vNoeyW

var canadamap = document.getElementById("canada-map"),
    provinceInfo = document.getElementById("provinceInfo"),
    allProvinces = canadamap.querySelectorAll("g");
    canadamap.addEventListener("click", function(e){ 
        var province = e.target.parentNode;
        if(e.target.nodeName == "path") {
        for (var i=0; i < allProvinces.length; i++) {
            allProvinces[i].classList.remove("active");
        }
        province.classList.add("active");
        var provinceName = province.querySelector("title").innerHTML,
        provincePara = province.querySelector("desc p");
        sourceImg = province.querySelector("img"),
        imgPath = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/";
        provinceInfo.innerHTML = "";
        provinceInfo.insertAdjacentHTML("afterbegin", "<img src="+imgPath + sourceImg.getAttribute('xlink:href')+" alt='"+sourceImg.getAttribute('alt')+"'><h1>"+provinceName+"</h1><p>"+provincePara.innerHTML+"</p>");
        provinceInfo.classList.add("show");
        }
    })

Create legends split panels Google earth engine

I’ve got a problem regarding checkboxes (or widgets, generally) and split panel. I created a split panels that allows users to see two images simultaneously for comparisons…one image for any panel (left panel and right panel). Also, I created another one panel on the right part of the map with a gradient colours legend with values from 0 to 1 etc…

So, with the following code:

var palettes = require('users/gena/packages:palettes');
var Vis = palettes.colorbrewer.RdYlGn[11].reverse();

exports.splitt=function(images){var colorizedVis = {
  min: 0.0,
  max: 1.0,
  palette: Vis,
};

// Create the left map, and have it display layer 0.
var leftMap = ui.Map();
leftMap.add(createLegend())
leftMap.setControlVisibility(true);
var leftSelector = addLayerSelector(leftMap, 0, 'top-left');
//Map.addLayer(leftMap, viz);

// Create the right map, and have it display layer 1.
var rightMap = ui.Map();
rightMap.add(createLegend())
rightMap.setControlVisibility(true);
var rightSelector = addLayerSelector(rightMap, 1, 'top-right');

var checkbox = ui.Checkbox('Activate/Deactivate Split Panel', false);
checkbox.onChange(function(checked) {
  if (checked) {
    ui.root.widgets().reset([leftMap]);
  } else {
    ui.root.widgets().reset([splitPanel]);
  }
});
print(checkbox)

// Adds a layer selection widget to the given map, to allow users to change
// which image is displayed in the associated map.
  function addLayerSelector(mapToChange, defaultValue, position) {
  var label = ui.Label('Choose an image to visualize');

  // This function changes the given map to show the selected image.
  function updateMap(selection) {
    var heightLab = ui.Label({value:'Susceptibility Scale',
    style: {fontWeight: 'bold', fontSize: '16px', margin: '10px 5px'}
    });
    
    mapToChange.layers().set(0, ui.Map.Layer(images[selection],colorizedVis));
  }

  // Configure a selection dropdown to allow the user to choose between images,
  // and set the map to update when a user makes a selection.
  var select = ui.Select({items: Object.keys(images), onChange: updateMap});
  select.setValue(Object.keys(images)[defaultValue], true);

  var controlPanel =
      ui.Panel({widgets: [label, select, ], style: {position: position}});
  mapToChange.add(controlPanel);
}

//create the first panel 
function createLegend() {
    var legend = ui.Panel({
    style: {
      position: 'bottom-right',
      padding: '8px 15px'
    },
    layout: ui.Panel.Layout.flow('horizontal')
  })

  // Create legend title
 var legendTitle = ui.Label({
    value: 'Susceptibility',
    style: {
      fontWeight: 'bold',
      fontSize: '10px',
      margin: '0 0 4px 0',
      padding: '0'
      }
  });

  // Add the title to the panel
  legend.add(legendTitle); 

  // create text on top of legend
  var min = colorizedVis.min;
  var max = colorizedVis.max
  
  var panel = ui.Panel({
      widgets: [
                ui.Label(min,{fontSize: '10px',textAlign: 'center'/*, stretch: 'horizontal'*/})
                ],
  layout: ui.Panel.Layout.flow('horizontal')
});
  legend.add(panel);
  
  var lon = ee.Image.pixelLonLat().select('longitude');
  var gradient = lon.multiply((colorizedVis.max-colorizedVis.min)/100.0)
  .add(colorizedVis.min);
  var legendImage = gradient.visualize(colorizedVis);
  var thumbnail = ui.Thumbnail({
    image: legendImage,
    params: {bbox:'0,0,100,10', dimensions:'180x10'}});
  thumbnail.style().set({padding: '1px', position: 'bottom-center', stretch: 'horizontal'});

  // add the thumbnail to the legend
  legend.add(thumbnail);
  
 var panel = ui.Panel({
      widgets: [
                ui.Label(max,{fontSize: '10px',textAlign: 'center', stretch: 'horizontal'})
                ],
  layout: ui.Panel.Layout.flow('horizontal')
});
  legend.add(panel);

  return legend
}

// Create a SplitPanel to hold the adjacent, linked maps.
var splitPanel = ui.SplitPanel({
  firstPanel: leftMap,
  secondPanel: rightMap,
  wipe: true,
  style: {stretch: 'both'}
})

// Set the SplitPanel as the only thing in the UI root.
ui.root.widgets().reset([splitPanel]);
var linker = ui.Map.Linker([leftMap, rightMap]);
leftMap.setCenter(13.1, 37.72604, 12);
}```

Is possible to show any image (for example 'true/false' image) and their image singularly?
I mean: if I wanted to show only one of the three images with its legend, using a checkbox or any kind of widget...What should I do? I tried using checkboxes but I still don't understand where/when I'm wrong.