How to fix the vulnerabilities in npm if I cannot upgrade the major version of dependency?

I have a high risk vulnerability from npm audit --production. This is dependency of snowflake-sdk. But I checked snowflake github it has "requestretry": "^6.0.0" in the package.json which mean is I cannot upgrade requestretry to 7.0.0. Is there any other way to fix this vulnerability? What if I upgrade requestretry to 7.0.0?

enter image description here

I am very new to npm and javascript, any help is appreciated!

Storing encrypted passwords client side? [closed]

I’m trying to build a javascript program that lets users encrypt strings using their passwords but I would like for this to be totally offline without requiring a server.

I’m using localstorage-slim for encrypting the strings that the user adds but I want it in a way that lets users enter the password and the localstorage data is available to them directly unencrypted for a few days. The reason I’m doing this is because I don’t want my users to be entering their password to decrypt the local storage data again and again everytime they want to get their encrypted string back.

Is it a good idea to store the password in local storage? What other alternatives are there for this?

I am having trouble getting a JavaScript while loop to run with a prompt and a counter

In my program I have a prompt first that asks for the user to enter a grade and then a while loop which says while the grade does not equal -1 to ask for the grade again. I have an else statement with a counter called “count” incrementing by one afterwards and then printing the grade within a table. The program then asks for the grade again until a -1 is pressed.

Here is my code.

 var count = 0;
 var total = 0;
 var grade;
 var avg = 0;
 grade = prompt('Enter grade(-1 to stop)');   
 while (grade != -1) {
 grade = prompt('Enter grade again');
 else
 count++;  
 document.write('<tr>');
 document.write('<td>Grade ' + count  '</td>');
 document.write('<td width="50">' + grade '</td>');
 document.write('</tr>');
   
 grade = prompt('Enter grade(-1 to stop)');
 total = total + grade;    
 document.write('</table>');
 avg = total / count;
 document.write('Semester Average: ' + avg); 

}

When a negative 1 is entered it should add of the total number of all grades, and then calculate an average by dividing the count by the total. This will not run. Any tips would be appreciated.

Why website is broken when i reload the page?

I used fuse template to build an angular project. I made it but when i reload the page website are broken. This is the mistake output:

Server Error 404 – File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

Someone told that it is about app.module.ts but i do not know how to fix it. Could anyone help me to solve this problem?
Here is my app.module code=>

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ExtraOptions, PreloadAllModules, RouterModule } from '@angular/router';
import { MarkdownModule } from 'ngx-markdown';
import { FuseModule } from '@fuse';
import { FuseConfigModule } from '@fuse/services/config';
import { FuseMockApiModule } from '@fuse/lib/mock-api';
import { CoreModule } from 'app/core/core.module';
import { appConfig } from 'app/core/config/app.config';
import { mockApiServices } from 'app/mock-api';
import { LayoutModule } from 'app/layout/layout.module';
import { AppComponent } from 'app/app.component';
import { appRoutes } from 'app/app.routing';

const routerConfig: ExtraOptions = {
    preloadingStrategy       : PreloadAllModules,
    scrollPositionRestoration: 'enabled'
};

@NgModule({
    declarations: [
        AppComponent
    ],
    imports     : [
        BrowserModule,
        BrowserAnimationsModule,
        RouterModule.forRoot(appRoutes, routerConfig),

        // Fuse, FuseConfig & FuseMockAPI
        FuseModule,
        FuseConfigModule.forRoot(appConfig),
        FuseMockApiModule.forRoot(mockApiServices),

        // Core module of your application
        CoreModule,

        // Layout module of your application
        LayoutModule,

        // 3rd party modules that require global configuration via forRoot
        MarkdownModule.forRoot({})
    ],
    bootstrap   : [
        AppComponent,
    ],
})
export class AppModule
{
}

How do I make the navbar stay within the parent div (hero image) regardless of screen size?

I adjusted it based on my screen size, and I’ve tried using both relative and absolute positions for .navbar, but when I open it on my laptop the navbar content overflows the parent image, setting overflow to hidden doesn’t fix the issue since i want it to stay over the bottom of the image at all times regardless of screen size. Here’s the jsfiddle https://jsfiddle.net/Montinyek/4dbf5p9e/1/


body, html {
  height: 100%;
  margin: 0;
  padding:0;
  font-family: Times, Times New Roman, serif;
}

.hero-image {
  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.2)), url(./hero.jpg);
  height: 80%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  overflow: hidden;
}

.hero-text {
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #f2f2f2;
}


h1 {
  padding: 80px 60px;
  border: 1px solid #f2f2f2;
  border-radius: 5px;
}

.nav-container {
  display: inline-block; 
  position: relative;
  top: 87%;
}

.navbar {
  overflow: hidden;
  height: 100px;
  display: inline-flex;
  gap: 70px; 
  align-items: center;
  justify-content: center;
  width: 99vw;
  
}

.navbar a.main {
  color: #f2f2f2;
  padding-left: 47px;
  padding-right: 47px;
  padding-top: 10px;
  padding-bottom: 10px;
  border: 1px solid #f2f2f2;
  border-radius: 5px;
  text-decoration: none;
  font-size: 20px;
  margin: 0px;
  transition: all 0.3s;
  display: block; 
}


.navbar a.main:hover  {
  background-color: #ddd;
  transform: scale(1.3);
  color: black; 
}

.dropdown-content {
  visibility: none;
  opacity: 0;
  pointer-events: none;
  position: absolute;
  left: 64.6%;
  top: 80%;
  border-radius: 5px;
  background-color: black;
  min-width: 160px; 
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
  z-index: 1;
  transition: all 0.5s;
  
}

.dropdown-content a {
  float: none;
  color: #ddd;
  padding: 12px;
  text-decoration: none;
  display: block;
  text-align: center;
  transition: all 0.5s;
  font-size: 1.5rem;
}

.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

.dropdown:hover .dropdown-content {
  display: block;
  opacity: 1;
  visibility: visible;
  pointer-events: auto;
}


</style>
<body>


  <div class="hero-image">
    <div class="hero-text">
        <h1 style="font-size:50px">Welcome</h1></div>
        <div class="nav-container">
          <div class="navbar">
            <a class="main" href="#home">Home</a>
            <a class="main" href="#mission">Mission</a>
            <a class="main" href="#news">Contact</a>
            <div class="dropdown">
              <a class="main" href="#news">More<i class="fa fa-caret-down"></i></a>
              <div class="dropdown-content">
                <a style="color:rgb(238, 92, 92);" class="link" href="./index5.html">Gift</a>
                <a href="./index7.html">Travel</a>
                
              </div>
            </div> 
          </div></div>
      </div>

      
    
</body>
</html>``` 

Time for populating a UI dynamically increases linearly with each try

Requirement:

  1. User will enter “Number of Containers” and “Number of Controls”
  2. Random input elements (numeric, checkbox, etc) will be created and equally distributed among the containers
  3. When user clicks on “Create” again, the input elements shown in the UI will be deleted and new set of random input elements will be populated again
    Sample UI with Controls Populated

Issue:
Every time I create new set of input elements, the time taken for creating increases linearly up to a point then decreases little and increases again
Time Log example

I use the below code to empty the container and create input elements

Emptying the container div

node.innerHTML = ""

Creating a numeric control with label

function createNumber(display){
let controlWrap = document.createElement("div");
let label = document.createElement("label")
let control = document.createElement("input")
control.type = "number";
label.append("Numeric Input");
label.append(control);
controlWrap.append(label);
controlWrap.style.display = display;
controlWrap.classList.add("ctrl");
return controlWrap; }

Find the entire code below,

//Constands
const CTRL_DISPLAY_TYPE = "block"

//Selection
const numOfContainers = document.querySelector("#numOfContainers");
const numOfControls = document.querySelector("#numOfControls");
const createContainersBtn = document.querySelector("#create");
const containerWrapper = document.querySelector(".containerWrapper");
const controlHeading = document.querySelectorAll(".ctrlHeading");

//Event Listeners
createContainersBtn.addEventListener("click",createContainers);
controlHeading.forEach(element => element.addEventListener("click"),expandControl);

//Support-functions
function createControl(newControlContainer){
    let newControlWrapper = document.createElement("div")
    newControlWrapper.classList.add("ctrlWrapper");

    let newControl = createNumber(CTRL_DISPLAY_TYPE);
    newControlWrapper.appendChild(newControl);
    newControlContainer.appendChild(newControlWrapper);

}

function createNumber(display){
    let controlWrap = document.createElement("div");
    let label = document.createElement("label")
    let control = document.createElement("input")
    control.type = "number";
    label.append("Numeric Input");
    label.append(control);
    controlWrap.append(label);
    controlWrap.style.display = display;
    controlWrap.classList.add("ctrl");
    return controlWrap;
}

function calculateControlPerContainer(numOfContainers,numOfControls,maxLimit){
    let controlsPerContainer = []
    let pendingControls = numOfControls%numOfContainers
    let controlPerContainerNum = Math.floor(numOfControls/numOfContainers)
    for (let i=0;i<numOfContainers;i++){
        if (pendingControls>0){
            newControlsPerContainer=controlPerContainerNum+1;
            controlsPerContainer.push(newControlsPerContainer);
            --pendingControls;
        }
        else{
            controlsPerContainer.push(controlPerContainerNum);
        }
    }
    return controlsPerContainer
}

function expandControl(event){
    const control = event.currentTarget.nextElementSibling;
    if (control.style.display === "none"){
        control.style.display = "block";
    }
    else {
        control.style.display = "none"
    }
}

//utility-functions
function removeChild(node){
    while(node.firstChild){
        node.removeChild(node.firstChild);
    }
}

function clearNodeData(node){
    node.innerHTML = ""
}

//main-Functions
function createContainers(event){
    console.time("Deleting controls");
    const controlsPerContainer = calculateControlPerContainer(parseInt(numOfContainers.value),parseInt(numOfControls.value));
    clearNodeData(containerWrapper);
    //removeChild(containerWrapper);
    console.timeEnd("Deleting controls");  
    console.time("populating controls");
    controlsPerContainer.forEach(num=>{        
        let newControlContainer = document.createElement("div")
        newControlContainer.classList.add("ctrlContainer");
        for(let j=0;j<num;j++){
            createControl(newControlContainer);
        }
        containerWrapper.appendChild(newControlContainer);
    }) 
    console.timeEnd("populating controls");   
}
* {
    box-sizing: border-box;
}

html, body {
    margin: 0;
    padding: 0;
    border: 0;
    height:100%
}

.containerWrapper{
    display:flex;
    flex-direction: row;
    height: 90%;
}

.ctrlContainer{
    /* flex-grow:1; */
    flex-shrink: 0;
    border-style: solid;
    border-width: 0.5px;
    margin:0 2px;
    flex-basis: calc(25% - 4px);
    align-items: stretch;
    display:flex;
    flex-direction: column;
    overflow: auto;
}

.ctrlWrapper{
    border-style: solid;
    border-width: .5px;
    margin:2px
}

.ctrlHeading{
    display:block;
    width: 100%;
    text-align: left;
    border: 0;
}

.ctrl{
    display:none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Controls</title>
    <link rel="stylesheet" href="style/main.css">
</head>
<body>
    <label for="numOfContainers">Number of Containers</label>
    <input type="number" id="numOfContainers" name="numOfContainers" min="1" max="500" value="100">
    <label for="numOfControls">Number of Controls</label>
    <input type="number" id="numOfControls" name="numOfControls" min="1" max="1500" value="1500"><br>
    <button id="create">Create</button>
    <div class="containerWrapper">
        <!-- <div class="ctrlContainer">
            <div class="ctrlWrapper">
                <button class="ctrlHeading">Checkbox</button>
                <input class="ctrl" type="checkbox">
            </div>
            <div class="ctrlWrapper">
                <button class="ctrlHeading">Checkbox</button>
                <input class="ctrl" type="checkbox">
            </div>
        </div>
        <div class="ctrlContainer">2</div>
        <div class="ctrlContainer">3</div> -->
    </div>
    <script type="module" src="scripts/MainBackup.js"></script>
</body>
</html>

I tried analyzing using chrome developer tools and could see “append” function is taking more total time. Please let me know if I am doing something wrong in deleting or adding controls.

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘data’), map is not working?

I have a API this is working fine in console. but when I’m using map this is not working giving error.

My Code:-

function GetEgyptStates() {
  const [egyptData, setEgyptData] = React.useState(null);

  React.useEffect(() => {
    axios.get('http://localhost:3000/states-and-districts.json').then((response) => {
      setEgyptData(response.data);
      console.log(response.data.Egypt.Assuit);
    });
  }, []);

  if (!egyptData) return null;

  return (
    <div>
        {egyptData.response.data.Egypt.Assuit.map((item) => (
          <li>{item}</li>
        ))}
    </div>
  );
}

ThankYou for your Support!

How do I get a nested anonymous function to open links in a new window

How do I make this Javascript to open on a new page when
I’ve created an allSelect variable referencing all select elements nested within the govLinks form (it works but opens on the same window).

Within the nested anonymous function, I need to retrieve tge value of the property of evt.target and store it in the linkURL variable

Within the nested anonymous function I also need to use the window.open() method to open a new browser or any window options. Store the window under the newWin variable.

Any help will be appreciated.

Here is my current Javascript code.

// Function invoked when window is loaded, and it is an anonymous function

window.onload = function() {

// Get all select elements in 'govlinks'

var allSelect = document.getElementById("govLinks").querySelectorAll("select");


// Loop on all the select elements and attach an event to them

for (var i = 0; i < allSelect.length; i++) {

allSelect[i].onchange = function (evt) {

console.log(evt.target.value);

location.href = evt.target.value; // Update location href
}

}

}

HTML:

     <article>
     <form id="govLinks" name="govLinks">
     <h1>Government Sites on the Web</h1>

     <p>Select a site from one of the drop-down lists below.</p>
     <table>
        <tr><td>Executive Branch</td>
            <td><select name="executive" id="executive" class="optionLinks">
                <option value="#">Select a Web site</option>
                <option value="http://www.whitehouse.gov">The White House</option>
                <option value="http://www.usda.gov">Department of Agriculture</option>
                <option value="http://www.doc.gov">Department of Commerce</option>
                <option value="http://www.defenselink.mil">Department of Defense</option>
                <option value="http://www.ed.gov">Department of Education</option>
                <option value="http://www.energy.gov">Department of Energy</option>
                <option value="http://www.hhs.gov">Department of Health and Human 
       Services</option>
                <option value="http://www.whitehouse.gov/homeland">Department of Homeland 
      Security</option>
                <option value="http://www.hud.gov">Department of Housing and Urban 
       Development</option>
                <option value="http://www.doi.gov">Department of the Interior</option>
                <option value="http://www.usdoj.gov">Department of Justice</option>
                <option value="http://www.dol.gov">Department of Labor</option>
                <option value="http://www.state.gov">Department of State</option>
                <option value="http://www.ustreas.gov">Department of the Treasury</option>
                </select>
            </td>
        </tr>
        <tr><td>Legislative Branch</td>
            <td><select name="legislative" id="legislative" class="optionLinks">
                <option value="#">Select a Web site</option>
                <option value="http://www.house.gov">House Web Site</option>
                <option value="http://clerk.house.gov/">Clerk of the House</option>
                <option value="http://www.senate.gov">Senate Web Site</option>
                <option 
         
      value="http://www.senate.gov/general/contact_information/senators_cfm.cfm">Senators' 
      Web Sites</option>
                <option 
 
 
 
 
 
 value="http://www.senate.gov/artandhistory/history/common/generic/Senate_Historical_Office.htm">Senate Historic Office</option>
                <option value="http://www.cq.com">Congressional Quarterly</option>
                <option value="http://www.loc.gov/">Library of Congress</option>
                <option value="http://www.gao.gov/">Government Accountability Office</option>
                <option value="http://www.cbo.gov/">Congressional Budget Office</option>
                </select>
            </td>
        </tr>
        <tr><td>Judicial Branch</td>
            <td><select name="judicial" id="judicial" class="optionLinks">
                <option value="#">Select a Web site</option>
                <option value="http://www.uscourts.gov">U.S. Courts</option>
                <option value="https://www.supremecourt.gov/">U.S. Supreme Court</option>
                <option value="http://www.uscourts.gov/courtsofappeals.html">U.S. Courts of Appeals</option>
                </select>
            </td>
        </tr>
        <tr><td>State Governments</td>
            <td><select name="state" id="state" class="optionLinks">
                <option value="#">Select a Web site</option>
                <option value="http://www.statelocalgov.net/index.cfm">State and Local Government on the Net</option>
                <option value="http://www.statelocalgov.net/state-al.cfm">Alabama</option>
                <option value="http://www.statelocalgov.net/state-ak.cfm">Alaska</option>
                <option value="http://www.statelocalgov.net/state-az.cfm">Arizona</option>
                <option value="http://www.statelocalgov.net/state-ar.cfm">Arkansas</option>
                <option value="http://www.statelocalgov.net/state-ca.cfm">California</option>
                <option value="http://www.statelocalgov.net/state-co.cfm">Colorado</option>
                <option value="http://www.statelocalgov.net/state-ct.cfm">Connecticut</option>
                <option value="http://www.statelocalgov.net/state-de.cfm">Delaware</option>
                <option value="http://www.statelocalgov.net/state-dc.cfm">District of Columbia</option>
                <option value="http://www.statelocalgov.net/state-fl.cfm">Florida</option>
                <option value="http://www.statelocalgov.net/state-ga.cfm">Georgia</option>
                <option value="http://www.statelocalgov.net/state-hi.cfm">Hawaii</option>
                <option value="http://www.statelocalgov.net/state-id.cfm">Idaho</option>
                <option value="http://www.statelocalgov.net/state-il.cfm">Illinois</option>
                <option value="http://www.statelocalgov.net/state-in.cfm">Indiana</option>
                <option value="http://www.statelocalgov.net/state-ia.cfm">Iowa</option>
                <option value="http://www.statelocalgov.net/state-ks.cfm">Kansas</option>
                <option value="http://www.statelocalgov.net/state-ky.cfm">Kentucky</option>
                <option value="http://www.statelocalgov.net/state-la.cfm">Louisana</option>
                <option value="http://www.statelocalgov.net/state-me.cfm">Maine</option>
                <option value="http://www.statelocalgov.net/state-md.cfm">Maryland</option>
                <option value="http://www.statelocalgov.net/state-ma.cfm">Massachusetts</option>
                <option value="http://www.statelocalgov.net/state-mi.cfm">Michigan</option>
                <option value="http://www.statelocalgov.net/state-mn.cfm">Minnesota</option>
                <option value="http://www.statelocalgov.net/state-ms.cfm">Mississippi</option>
                <option value="http://www.statelocalgov.net/state-mo.cfm">Missouri</option>
                <option value="http://www.statelocalgov.net/state-mn.cfm">Montana</option>
                <option value="http://www.statelocalgov.net/state-ne.cfm">Nebraska</option>
                <option value="http://www.statelocalgov.net/state-nv.cfm">Nevada</option>
                <option value="http://www.statelocalgov.net/state-nh.cfm">New Hampshire</option>
                <option value="http://www.statelocalgov.net/state-nj.cfm">New Jersey</option>
                <option value="http://www.statelocalgov.net/state-nm.cfm">New Mexico</option>
                <option value="http://www.statelocalgov.net/state-ny.cfm">New York</option>
                <option value="http://www.statelocalgov.net/state-nc.cfm">North Carolina</option>
                <option value="http://www.statelocalgov.net/state-nd.cfm">North Dakota</option>
                <option value="http://www.statelocalgov.net/state-oh.cfm">Ohio</option>
                <option value="http://www.statelocalgov.net/state-ok.cfm">Oklahoma</option>
                <option value="http://www.statelocalgov.net/state-or.cfm">Oregon</option>
                <option value="http://www.statelocalgov.net/state-pa.cfm">Pennsylvania</option>
                <option value="http://www.statelocalgov.net/state-ri.cfm">Rhode Island</option>
                <option value="http://www.statelocalgov.net/state-sc.cfm">South Carolina</option>
                <option value="http://www.statelocalgov.net/state-sd.cfm">South Dakota</option>
                <option value="http://www.statelocalgov.net/state-tn.cfm">Tennessee</option>
                <option value="http://www.statelocalgov.net/state-tx.cfm">Texas</option>
                <option value="http://www.statelocalgov.net/state-ut.cfm">Utah</option>
                <option value="http://www.statelocalgov.net/state-vt.cfm">Vermont</option>
                <option value="http://www.statelocalgov.net/state-va.cfm">Virginia</option>
                <option value="http://www.statelocalgov.net/state-wa.cfm">Washington</option>
                <option value="http://www.statelocalgov.net/state-wv.cfm">West Virginia</option>
                <option value="http://www.statelocalgov.net/state-wi.cfm">Wisconsin</option>
                <option value="http://www.statelocalgov.net/state-wy.cfm">Wyoming</option>
                </select>
            </td>
        </tr>
     </table>
     </form>     
  </article>      

javascript
html
for-loop

Getting readable date from ISO

I’m using vue.js and moment.js and I can’t get this date into a readble format.

2022-03-16T13:00:00.000000Z

I’m looking for something like 16th March 2022 – 1pm

I’ve tried this thus far…

    var s = '2022-03-16T13:00:00.000000Z';
    var b = s.split(/D+/);
    console.log( new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6])));

and

<span>{{ '2022-03-16T13:00:00.000000Z' | moment("DD-MM-YY") }}</span>

How do I assign class properties values based on existing keys in an object I send?

I have a class

export class Example {
    id: number = 0;
    a: string = '';
    b: string = '';

    constructor(data: any) {
        Object.keys(data).filter(key => key in data).forEach((key: string) => this[key] = data[key]);
        return this;
    }
}

I want to be able to send an object in the constructor, and based on that object it will assign the values in which the key matches the property of the class. This is because I might send an object which has additional key properties, but I do not want to put in my class the values that are not defined in my class. This is why I don’t use Object.assign(this, data); because it will add additional properties to my class if the data object has them.

The problem with the code in the constructor above is that it’s not letting me use this[key], the error being Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Example'. Can anyone help me with this?

Rename a file if already exists in javascript by increment file_1.txt,file_2.txt like that. This code didn’t works

I tried this code, It creates a file like file.txt as file_1.txt after that it didn’t increased it ,again i gave a filename as file.txt it again shows file_1.txt. I need to increase the value like file_1.txt,file_2.txt,file_3.txt like that.

 while (await client.exists(path+'/'+filename)) {
        var ext = filename.split('.');
        if (i == 0) {
            i = i + 1;
            filename = ext[0] + "_" + i + "." + ext[1]
            i++;
            var newfilename = filename
            // await client.put(buff,path+'/'+newfilename)
            console.log(newfilename)
           
        } else {
            file = ext[0].substr(0, ext[0].lastIndexOf("_" + i));
            i = i + 1;
            filename = filename + "_" + i + "." + ext[1]
        }

    }

While nested in Forloop Time Complexity

What is the Time Complexity of my solution?

Question:
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Solution (JavaScript)

var removeElement = function(nums, val) {
  let rightIndex = nums.length - 1
  let count = 0
    
  //To set the length, iterate and count val
  for(let i = 0; i < nums.length; i++){
    if(nums[i] == val){
      count++
    }
  }
  
  let length = nums.length - count
  //As iterating, if 2 appears, replace it with value located in rightIndex
  for (let i = 0; i <= length; i++ ){
    if(nums[i] == val){
      //What if the value in rightIndex == val?
      while(nums[rightIndex] == val){
        rightIndex--
      }
      nums[i] = nums[rightIndex]
      rightIndex--
      
    } else {
      nums[i] = nums[i]
    }
    
  }
  return length
};

ReactDOM.render is not rendering element created through React.createElement

I created a modal component that utilizes React’s context, and hooks for easy usage. But for some reason, the element that I want to render in the modal doesn’t appear.

Here’s my code for the ModalContainer which contains the provider and the modal

ModalContainer.tsx

export type ModalElement =
  | React.ComponentClass<any, any>
  | React.FC<any>
  | JSX.Element;

const ModalContainer: React.FC = ({ children }) => {
  const [visible, setVisible] = useState(false);

  const modal = useRef<HTMLDivElement>(null);

  const showModal = (element: ModalElement) => {
    if (element && modal.current) {
      if (React.isValidElement(element)) {
        ReactDOM.render(element, modal.current);
      } else {
        const el = React.createElement(
          element as React.ComponentClass<any, any> | React.FC<any>,
          {}
        );

        ReactDOM.render(el, modal.current);
      }
      setVisible(true);
    }
  };

  const dismissModal = () => {
    setVisible(false);
  };

  return (
    <ModalContext.Provider value={{ showModal, dismissModal }}>
      {children}
      <Modal visible={visible} onClose={dismissModal} ref={modal} />
    </ModalContext.Provider>
  );
};

export default ModalContainer;

useModal.ts

export const useModal = (element: ModalElement) => {
  const context = useContext(ModalContext);

  if (!context) {
    Error(`Can't get modal context`);
  }

  const show = useCallback(() => {
    context.showModal(element);
  }, [context, element]);

  const dismiss = useCallback(() => {
    context.dismissModal();
  }, [context]);

  return [show, dismiss];
};

In a way that you’ll use it as such:

const DivModal: React.FC = () => {
  return <div>Test</div>
}

const Component: React.FC = () => {
  const [show, dismiss] = useModal(DivModal);
  
  const onClick = () => {
    show();
  }

  return <button onClick={onClick}/>
}

The problem seems to happen when I create an element using React.createElement in the ModalContainer.tsx found specifically in this line:

const el = React.createElement(
  element as React.ComponentClass<any, any> | React.FC<any>,
  {}
);

ReactDOM.render(el, modal.current);

The modal renders properly if I replace el in the render function with a test JSX such as <div>test</div>. Can’t really figure out what’s wrong so I’ll post it here just in case anyone knows what the problem is. Thanks!