File Brows Progress Bar Without Ajax (Only HTML CSS and JS/ Jquery)

  • I’ve browsing a large file, so I want to show the file browsing
    progress bar.
  • I do not need to use ajax,
  • I just want to show the progress bar and progress percentage when
    browsing or dragging the file from the browser.

But unfortunately i didn’t get a reference without ajax that’s why i just posting here

sample code

  function uploadFile() {
    var file = _("file1").files[0];
    var formdata = new FormData();
    formdata.append("file1", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "index.php"); 
    ajax.send(formdata);
  }

 function progressHandler(event) {
   _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + 
   event.total;
   var percent = (event.loaded / event.total) * 100;
  _("progressBar").value = Math.round(percent);
  _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
 }


function completeHandler(event) {
  _("status").innerHTML = event.target.responseText;
  _("progressBar").value = 0; //wil clear progress bar after successful upload
}



   <div class="col-md-6">                               
       <label class="lbl mandatory" for="">Image</label>
       <input type="file" name="file1" id="file1" onchange="uploadFile()"><br>
       <progress id="progressBar" value="0" max="100" style="width:300px;"> 
       </progress>
          <h3 id="status"></h3>
        <p id="loaded_n_total"></p>
   </div>

How to trigger hover action using javascript?

I want to simulate mouse hover on this site
on this element using only javascript with selenium.

//*[@id="main"]/div/div/div[3]/div/div[2]/div/div[3]/div[2]/div/div[2]/div/div/div[1]/svg/g[5]/g/g[80]

I have looked at various posts like this and this.
However, nothing seems to be working on this site.

I tried using this code, but it isn’t working on the site.

const mouseoverEvent = new Event('mouseover');
$x('//*[@id="main"]/div/div/div[3]/div/div[2]/div/div[3]/div[2]/div/div[2]/div/div/div[1]/svg/g[5]/g/g[80]').dispatchEvent(mouseoverEvent)

Due to some problems I can only use javascript and not Actionchains like most posts describe. Any solution without ActionChains should work fine.

Is it possible to simulate the mouse hover on the element?
Also, why does the code work on some sites but not on others, for example, works on this?

Opening file with js

Im making a discord.js bot. Im trying to make that whenever someone types a command on discord it opens a program on my pc.

client.on(“message”, (message) => {
if(message.content == “!ping”){
;//here I want to open a program on my pc
}
});

Two toggle switch at the local storage

I want to try the dark mode switch for laptop and mobile. So, I used two toggles and also used local storage. I have a problem. In two toggles, only work first toggle for dark mode. I want to run two toggle switches at the same time. When I want to switch on, another toggle also switches on automatically.

HTML

 <li><a id="sidebar-a">Darkmode
<input type="checkbox" id="switch"><label class="label2" for="switch">Toggle</label>

<li><a id="sidebar-a">Darkmode
    <input type="checkbox" id="switch2"><label class="label6" for="switch2">Toggle</label>

CSS

  body.light {
                --body-back: #F7F7F8;
               
                --h1-color: #42493e;
                --a-color:#39393A;

                --setting-tool:#696969;
                --quick-bar:#E5E5E5;
             
                --quick-bar2:#dee4e7;
              
      
            }
    
            body.dark{
                --body-back:#0e0e10;
                
                --h1-color:orange;
                --a-color:#dfdfe1;

             
                --quick-bar:#464649;

          
                --quick-bar2:#37474f;
              
            
            }
    
            body{
                background: var(--body-back);
            }
    
    
    
    
    
    
    







    
    
            input[type="checkbox"]{
                height: 0;
                width: 0;
                visibility: hidden;
            }
            .label2{

enter code here

                cursor: pointer;
                text-indent: -9999px;
                width: 46px;
                height: 23px;
                background: #c4c4c4;
                display: block;
                border-radius: 100px;
                position: absolute;
                margin-left: 124px;
                margin-top: -37px;
        
            }
            .label2::after{
                content: "";
                position: absolute;
                top: 2.4px;
                left: 2.5px;
                width: 20px;
                height: 20px;
                background:#34393f ;
                border-radius: 90px;
                transition: 0.3s;
            }
     
    
            input:checked + .label2{
                background: black;
            }
            input:checked + .label2::after{
                left: calc(100% - 2.5px);
                transform: translateX(-100%);
            }
    
            input:checked + .label6{
                background: black;
            }
            input:checked + .label6::after{
                left: calc(100% - 2.5px);
                transform: translateX(-100%);
            }
    
    
    
    
    
    
    
    
            .label6{
                cursor: pointer;
                text-indent: -9999px;
                width: 46px;
                height: 23px;
                background: #c4c4c4;
                display: block;
                border-radius: 100px;
                position: absolute;
                margin-left: 124px;
                margin-top: -37px;
        
            }
            .label6::after{
                content: "";
                position: absolute;
                top: 2.4px;
                left: 2.5px;
                width: 20px;
                height: 20px;
                background:#34393f ;
                border-radius: 90px;
                transition: 0.3s;
            }










const chkToggle = document.querySelector("#switch")
const theme = localStorage.getItem("theme")

document.body.classList.toggle(theme === "dark" ? "dark" : "light")

if (theme == "dark"){
    chkToggle.checked = true
}

else {
    chkToggle.checked = false
}

chkToggle.addEventListener("change", function (e){

    e.preventDefault()
    if (this.checked) {
        document.body.classList.add("dark")
        document.body.classList.remove("light")
        localStorage.setItem("theme", "dark")
        console.log("dark mode");
    }
    else{
        document.body.classList.add("light")
        document.body.classList.remove("dark")
        localStorage.setItem("theme", "light")
        console.log("light mode"); 
    }
})

It doesn’t work

Illegal constructor Java script

I am new to Javascript and so I am just trying to implement a basic queue, but I get the error: Uncaught TypeError: Illegal Constructor. I really don’t know what is wrong. Here is my code.

class node{
  constructor(id,value){
    this.id = id;
    this.value = value;
    this.next = null;
  }
  getId(){
    return this.id;
  }
  getValue(){
    return this.value;
  }
  setValue(value){
    this.value = value;
  }
  getNext(){
    return this.next;
  }
  setNext(next){
    this.next = next;
  }
}


class queue{
  constructor(){
    this.head = null;
    this.size = 0;
    this.tail = null;
  }
  enqueue(value){
    let newNode = new Node(this.size,value); //This is line 39
    if (this.size === 0){
      this.head = newNode;
      this.tail = newNode;
      this.size++;
      return;
    }
    this.tail.next=newNode;
    this.tail = newNode;
    this.size +=1;
  }
  dequeue(){
    if (this.size > 0){
      let temp = this.head.getValue();
      this.head = this.head.getNext();
      this.size --;
      return temp;
    }
    return null;
  }

}


var q= new queue();
q.enqueue(1)
console.log(q.dequeue);

It throws it on the line in enqueue where I make a new node. Is there some limitation to making objects in objects that I don’t know? I have attached the error message. Line 39 in the where I make a new node object.Error Message

Finding Duplicates in array of object in javascipt by map method

I am trying to remove duplicate from an array of object in Javascript. Below is the code which doesnot work, it is creating Array of map of size 4.

let arr = [{id: 32, name: 'Name1', age: 88},
  {id: 33, name: 'Name2', age: 88},
  {id: 32, name: 'Name3', age: 88},
  {id: 1, name: 'Sam', age: 88},
  {id: 33, name: 'Name2', age: 88},
  {id: 2, name: 'Tom', age: 88}
];

console.log(arr)

let mp1 = new Map();
let uniqueElements = arr.map( obj => mp1.set(obj.id, obj))

console.log(uniqueElements);

Is there a strategy to use when you generate a manifest file and need to reference it in your library that you’re vending?

I’m vending a JS/TS library that generates some asset files (let’s say a list of keywords) and it generates a manifest file along side it. The manifest file knows some additional information about the generated asset files.

I’m currently letting the client define where the manifest file is being generated and ask them to provide the path as an attribute when they call my library.

This is an unnecessary step for the client as they don’t really use the manifest file.

Is there a strategy to hide away this extra step? I’m currently thinking to generate a fake npm package and put the manifest file in it and reference it. It works but it feels very hacky.

React Native – How to set a userState, which is fetching data form a API, initial value as blank?

so, I followed a tutorial to built a weather app which fetchs data from a API. The problem is I don’t want to show any data until the user type a city in ther search input. At the moment it is working fine, but it shows “undefined” as initial value when the app loads. How do I “hidden” the undefined value or how do I set it as blank?

What I’m getting as initial value

undefined, undefined, undefined
undefined
NaN°C
undefined

my code

function HomeScreen() {
  const initialValue = "zero";
  const [input, setInput] = useState('');
  const [data, setData] = useState([initialValue]);
  const [loading, setLoading] = useState(false);
  

  const api = {
    key: 'myKey',
    baseUrl: 'http://api.weatherapi.com/v1/',
  }
  const fetchDataHandle = useCallback(() => {
    setLoading(true);
    setInput("");
    axios({
      method: "GET",
      url: `http://api.weatherapi.com/v1/current.json?key=${api.key}&q=${input}&aqi=yes`,
    })
    .then(res=> {
      console.log(res.data);
      setData(res.data);
    })
    .catch(e => console.dir(e))
    .finally(() => setLoading(false));
  }, [api.key, input]);

  return (
    <View style={styles.container}>
           <View>
            <TextInput 
              placeholder='Enter city name...'
              onChangeText={text => setInput(text)}  
              value={input}
              placeholderTextColor={'black'}
              style={styles.textInput}
              onSubmitEditing={fetchDataHandle}
            />
            </View>
            {loading && (
              <View>
                <ActivityIndicator size={'large'} color="#000" />
              </View>
            )}

            {data && (
              <View style={styles.infoView}>
                <Text style={styles.cityText}>
                  {`${data?.location?.name}, ${data?.location?.region}, ${data?.location?.country}`}
                </Text>
                <Text style={styles.dateText}>{`${data?.location?.localtime}`}</Text>
                <Text style={styles.tempText}>{`${Math.round(data?.current?.temp_c)}°C`}</Text>
                <Text style={styles.conditionText}>{`${data?.current?.condition?.text}`}</Text>
                <Image style={styles.imageIcon} source={{uri: `${data?.current?.condition?.icon}`}} />
              </View>
            )}
        </View>
  );
}

How can I add an icon to an item in a todo list and then delete it when clicked?

I am learning JavaScript and I am trying to create a tolist. I have successfully been able to add new items to the list and able to cross off when each item is clicked but I need to:

  1. add a trash can icon when the item is added
  2. be able to add an event listener to each icon so that is deleted when clicked

Any help would be appreciated!

https://codepen.io/stefan927/pen/qBVLpxm

"<html>

<body onload="taskComplete()">
<div class="card">
<div class="card-body">
  <h3 class="card-title" id="header">Today's To Do List</h3>

  <form id="todo-form">
    <div class="input">
      <input type="text" onfocus="this.value=''" class="form-control" id="todo-input" 
       value="What do I want to do?">
    </div>
    <div class="form-group">
      <input type="button" onclick="addItemToTheList()" class="btn btn-secondary btn- 
       block" value="Add">
      <p> Click an item to cross it off! </p>
    </div>
  </form>
</div>
<ul class="list-group list-group-flush" id="todo-list">
  <li class="list-group-item">Pick up groceries
    <i class="fas fa-trash-alt"></i>
  </li>
  <li class="list-group-item">Finish essay
    <i class="fas fa-trash-alt"></i>
  </li>
  <li class="list-group-item">Soccer @ 5:00

    <i class="fas fa-trash-alt"></i>
</ul>
</div>
</body>

</html>"

" // create a function that adds new items to the list with a trash icon
function addItemToTheList() {
  const newItem = document.createElement("li");
  const input = document.getElementById("todo-input");
  newItem.innerHTML = input.value;
  input.value = "";
  document.getElementById("todo-list").appendChild(newItem);
  li.appendChild(i)

// Add click listener
newItem.addEventListener('click', done);
}

function done() {
this.className = "done";
this.removeEventListener('click',done);
}

// Initialize all listener for current undone tasks
function taskComplete() {
  var undoneItems = document.getElementsByClassName('undone');
  for(var i = 0; i < undoneItems.length; i++){
  undoneItems[i].addEventListener('click', done);  
 }
// Delete item from list when trash icon is clicked  
function deleteItem() {
   const icon = "fas fa-trash-alt";
   const i = document.createElement('i');
   const input = document.getElementById("todo-input");
   i.onclick = deleteItem;
   li.setAttribute('id', input.value);  
   li.classList.add("list-group-item");
   i.className = icon;

   }
}"

How to animate svg height with CSS upward?

I am working with a svg element and I want to animate the height increasing upwards of these elements. But they are growing downward probably due to svg coordinate system. How can I make it go upwards?

window.onload = function () {
    var x1 = document.querySelector('svg').viewBox.baseVal.height;
    var a = document.getElementById('wrapper1');
    var bgArray = [];
    for (var i = 1; i < a.children.length; i++) {
        bgArray.push((a.children[i].getBBox().height / x1) * 100);
    };
    bgArray.forEach((x, i) => a.children[i + 1].style.setProperty("--h1", x + '%'));
    bgArray.forEach((x, i) => a.children[i + 1].style.setProperty("--del", (i + 1) + 's')); //for staggered
}
.r1,
.r2 {    
    visibility: hidden;
    animation: moveHeight 2s ease-in var(--del) 1 forwards;
}

@keyframes moveHeight {
    0% {
        visibility: visible;
        height: 0%;
    }
    100% {
        visibility: visible;
        height: var(--h1);
    }
}
<!DOCTYPE html>
<html>

<body>

    <link rel="stylesheet" href="style.css">
    </link>

    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">

      <g class="wrapper1" id="wrapper1" >
    <rect x="10" y="20" width="120" height="120" stroke="black" fill="none"></rect>   
   <rect class="r1" id="r1" x="10" y="80" width="20" height="60" stroke="none" fill="orange"></rect>
    <rect class="r2" id="r2" x="31" y="100" width="20" height="40" stroke="none" fill="green"></rect>
  <!----> 
  </g>
  
  
  </svg>
    <script src="index.js"></script>
</body>

</html>

How to change the menu item’s color of sidebar when we click on it with css in React pls

I’m new to the React, my objective is to show color when I click on one of the Menu Item in Sidebar. Can anyone assist me in how to change color while clicking the menu item?

How to change the menu item’s color of sidebar when we click on it with Material-UI in React?
I referenced the post but it didn’t solve my problem.

https://i.stack.imgur.com/gInE5.png

Here is the Code:

import React from "react";
import { Collapse, List, ListItem } from "@material-ui/core";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ExpandLessIcon from "@material-ui/icons/ExpandLess";
import { useNavigate } from "react-router-dom";

const SidebarItem = ({ item }) => {

  const [collapsed, setCollapsed] = React.useState(true);
  const { title, enable, path, items } = item;
  let navigate = useNavigate();

  const toggleCollapse = () => {
    setCollapsed(prevValue => !prevValue); 
  }

  const onClick = () => {
    if (Array.isArray(items)) {
      console.log(items); 
      toggleCollapse();
    } else if (enable === true) {
      console.log(path);
      if (item[0]) {
        return navigate('');
      } else {
        return navigate("/setup/"+path);
      }
    }
  }

  let expandIcon;
  if (Array.isArray(items) && items.length) {
    expandIcon = !collapsed ? <ExpandLessIcon /> : <ExpandMoreIcon />;
  }

  return (
    <>
      <ListItem onClick={onClick} button dense>
        <div>{title}</div>
        {expandIcon}
      </ListItem>
      
      <Collapse in={!collapsed} timeout="auto" unmountOnExit>
        {Array.isArray(items) ? (
          <List>
            {items && items.map((subItem, index) => (
              <SidebarItem
                key={`${subItem}${index}`} 
                item={subItem}/>
            ))}
          </List>
        ) : null}
      </Collapse>
    </>
  );
}

const Sidebar = ({ items }) => {

  return (
    <>
      <List>
        {items && items.map((sidebarItem, index) => (
          <SidebarItem 
            key={`${sidebarItem}${index}`}
            item={sidebarItem}/>
        ))}
      </List>
    </>
  );
}

export default Sidebar;

React Router Shows Blank Page When Using . Stuck on this problem since a while

Here is the code of a component named topbar which refers to navbar of a page,
as soon as I save the page it appears to be blank.
Please help me to debug it as I am stuck for a while on it.
As soon as I comment the Link part , the page starts working instantly.

import { Link } from "react-router-dom";
import "./topbar.css";

export default function Topbar() {
  const user = true;
  return (
    <div className="top">
      <div className="topLeft">
        <i className="topIcon fab fa-facebook-square"></i>
        <i className="topIcon fab fa-instagram-square"></i>
        <i className="topIcon fab fa-pinterest-square"></i>
        <i className="topIcon fab fa-twitter-square"></i>
      </div>
      <div className="topCenter">
        <ul className="topList">
          <li className="topListItem">
            <Link className="link" to="/">
              HOME
            </Link>
          </li>
          <li className="topListItem">ABOUT</li>
          <li className="topListItem">CONTACT</li>
          <li className="topListItem">
            <Link className="link" to="/write">
              WRITE
            </Link>
          </li>
          {user && <li className="topListItem">LOGOUT</li>}
        </ul>
      </div>
      <div className="topRight">
        {user ? (
          <Link className="link" to="/settings">
            <img
              className="topImg"
              src="https://images.pexels.com/photos/1858175/pexels-photo-1858175.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500"
              alt=""
            />
          </Link>
        ) : (
          <ul className="topList">
            <li className="topListItem">
              <Link className="link" to="/login">
                LOGIN
              </Link>
            </li>
            <li className="topListItem">
              <Link className="link" to="/register">
                REGISTER
              </Link>
            </li>
          </ul>
        )}
        <i className="topSearchIcon fas fa-search"></i>
      </div>
    </div>
  );
}

How to set background-color on every page in wkhtmltopdf?

Here’s the generated pdf of wkhtmltopdf the second page doesn’t have a background color and border. I want to apply background-color and border for every page using laravel blade and wkhtmltopdf.

Here’s the body and footer CSS:

body {
  /* box-sizing: border-box; */
  font-family: "Open Sans", sans-serif;
  padding-top: 8px;
  padding-bottom: 0;
  margin-bottom: 0;
}

.container {
  background-color: #e8e8e8 !important;
  width: 99.2%;
  height: 759px !important;
  height: auto;
  border-top: 6px solid #383434;
  border-left: 6px solid #383434;
  border-right: 6px solid #383434;
  padding: 10px 0px 10px 0px;
}

.content {
  width: 306px !important;
  min-height: 350px;
  /* height: 753px !important; */
  background-color: #474747;
  display: flex;
  flex-direction: row;
  display: -webkit-box; /* wkhtmltopdf uses this one */
  color: white;
  border-radius: 2%;
  margin-left: 8px;
  margin-right: 4px;
  font-weight: 400;
  font-family: "Open Sans", sans-serif;
  font-size: 12px;
  page-break-inside: avoid;
}

.footer {
  background-color: black;
  width: 100%;
}
.top-section {
  background-color: #383434;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-right: 10px;
  padding-left: 10px;
  color: white;
  position: relative;
  display: table;
  width: 100.1%;
  font-family: "Open Sans", sans-serif;
  font-weight: 700;
  font-size: 16px;
}

.bottom-section {
  display: flex;
  display: -webkit-box; /* wkhtmltopdf uses this one */
  flex-direction: row;
  color: white;
  flex-wrap: wrap;
  -webkit-box-pack: center; /* wkhtmltopdf uses this one */
  justify-content: center;
  height: 175px;
}

Here’s the body laravel blade:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2? 
      family=Open+Sans:wght@400;700&display=swap" rel="stylesheet">
    <title>Proof of Order</title>
</head>

<body>
<!-- content -->
<div class="container">
    <table class="ct-table">
        <tr>
          <td>
            <div class="content">
                <div class="left-content">
                    <p>Product(s): 1,2,3,4</p>
                    <h>Material Type:</h>
                    <div class="type">
                        <div class="box"></div>
                        <div><p>Windows Graphics</p></div>
                    </div>
                    <p>Dimensions:</p>
                    <ul class="dimensions">
                        <li>1 - W: 49.5"| H: 54.25"</li>
                        <li>2 - W: 49.5"| H: 54.25"</li>
                        <li>3 - W: 49.5"| H: 35.25"</li>
                        <li>4 - W: 49.5"| H: 35.25"</li>
                    </ul>
                    <p>Options:</p>
                    <!--Addition of option list in table layout-->
                            <table class="option-list" id="option-list">
                                <tr>
                                  <td> <img src="price_point.svg" alt="" 
                                  class="option-logo"></td>
                                  <td> <p>Price Point 2/$4.00</p></td>
                                </tr>
                            </table>
                  
                            <table class="option-list">
                                <tr>
                                    <td> <img src="comments.svg" alt="" 
                                     class="option-logo"></td>
                                    <td> <p>Comments/Text: "Thanks for Shopping"</p> 
                                   </td>
                                </tr>  
                            </table>                           
                     
                            <table class="option-list">
                                <tr>
                                    <td><img src="logo.svg" alt="" class="option- 
                                      logo"></td>
                                    <td><p>Logo: logo.png</p></td>
                                </tr>  
                            </table>     
                     
                    </ul>
                       <!--Addition of quanity count in table layout-->
                    <table class="quantity-table">
                        <tr>
                            <td><p>Quantity: 2</p></td>
                            <td> <img src="qty.svg" alt=""  class="option-logo"></td>
                        </tr>  
                    </table>    
                </div>
                <div class="right-content">
                    <img src="me_1.jpg" alt="">
                </div>
             </div>
          </td>
        </tr>
        </table>
    </div>
</body>

</html>

Here’s the php code:

        $footerHtml = view()->make('admin.reports.final_proof.footer', compact('data'))- 
        >render();
        $pdf = PDF::loadView('admin.reports.final_proof.pdf', compact('data', 'products', 
        'no_of_products'))
        ->setOptions(array(
                'page-size' => 'A4',
                'margin-top' => 0,
                'margin-right' => 0,
                'margin-left' => 0,
                'margin-bottom' => 48,
                'encoding' => 'UTF-8',
                'footer-html' => $footerHtml,
                'enable-javascript' => true,
                'page-width'=>'279.5',
                'page-height'=>'216.0'
        ));

Here’s the footer laravel blade:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Proof of Order</title>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap" rel="stylesheet">
<script>
    var pdfInfo = {};
    var x = document.location.search.substring(1).split('&');
    for (var i in x) {
        var z = x[i].split('=', 2);
        pdfInfo[z[0]] = unescape(z[1]);
    }

    function getPdfInfo() {
        var page = pdfInfo.page || 1;
        var pageCount = pdfInfo.topage || 1;
        document.getElementById('pdfkit_page_current').textContent = page;
        document.getElementById('pdfkit_page_count').textContent = pageCount;
    }
</script>
</head>

<body onload="javascript:getPdfInfo()" style="margin-top:0;padding-top:0;">
    <div class="footer">
                <div class="top-section">
        <p>ORDER# MEC_EO-150454_AbingstonStopNGas</p>
        <p>PAGE 1 OF 1</p>
        <p>Designer: Ryan Test</p>
    </div>
    <div class="bottom-section">
        <div class="logo">
            <img src="monster_energy.png" alt="">
        </div>
        <div class="order">
             <!--Changing into table layout since flex/grid feature doesn't work-->
            <table class="option-list" id="option-list">
                <tr>
                  <td> <div class="order-type">
                    <img src="man.png" alt="">
                    <p>Ordered By</p>
                </div></td>
                  <td> <div class="text-content">
                    <p>Johnboy VanSampson</p>
                    <p>[email protected]</p>
                    <p>720-555-5698</p>
                </div></td>
                </tr>
            </table>
        </div>
        <div class="location">
              <!--Changing into table layout since flex/grid feature doesn't work-->
            <table class="option-list" id="option-list">
                <tr>
                  <td> <div  class="order-type">
                    <img src="shop.png" alt="">
                    <p>Project <br> Location</p>
                </div></td>
                  <td>  <div class="text-content">
                    <p>Abington Stop N Gas</p>
                    <p>Attn:Johnboy VanSampson</p>
                    <p>1562 Hiltop Pallace Blvd.</p>
                    <p>Swingtown, NJ 77895</p>
                    </div></td>
                </tr>
            </table>    
        </div>
        <div class="shipping">
              <!--Changing into table layout since flex/grid feature doesn't work-->
            <table class="option-list" id="option-list">
                <tr>
                  <td> <div class="order-type">
                    <img src="car.png" alt="">
                    <p>Shipping</p>
                </div></td>
                  <td> <div class="text-content">
                    <p>Abington Stop N Gas</p>
                    <p>Attn:Johnboy VanSampson</p>
                    <p>1562 Hiltop Pallace Blvd.</p>
                    <p>Swingtown, NJ 77895</p>
                    </div></td>
                </tr>
            </table>     
        </div>
    </div>
    </div>
</body>

</html>

React: pushing an updated object to an array when index is dynamic and changing

I have this layout below that if you click on any Tiles under each Category, it should push that tile to the dashboard on the right while also removing that tile from the sidebar. After I clicked on Tile 0 for example, it got removed from the sidebar and got added to Category 3 under Tile 0 on the right hand side dashboard.

enter image description here

My current dashboard state has this shape after the first add tile click:

[
   0: {
      id: 0,
      name: 'Category 3',
      tiles: [
         0: {
            category: 'Category 3',
            id: 'tile0',
            name: 'Tile 0'
         },
      ]
   }
]

The problem comes when I try to add the second tile of Categories that are not in order (Adding tiles from Category 2 first for example) Here is a portion my code:

const handleAddTiles = (categoryName, categoryIndex) {
    
    tiles.forEach(tile => {

       const categoryExists = dashboardState.map(category => 
       category.name).includes(tile.category)

       if (categoryExistOnDashboard) {
          setDashboardState((prevState) => {
             const categories = [...prevState];
             const categoryToUpdate = { ...categories[categoryIndex] }; // prints the state above
             const categoryTiles = [...categoryToUpdate.tiles, tile ]; // adds a new tile
             categoryToUpdate.tiles = categoryTiles; // replace previous tiles with new tiles

             // categories[categoryIndex] below is faulty indexing logic
             categories[categoryIndex] = { ...categoryToUpdate };

             return [...categories]; // set the state to our new copy
       }) 
       }
    })  
}

The above code works by grabbing the Category index from the sidebar when I click on the tiles, and it only works if I add down the list in order due to indexing. The problem is now if I decide to add tiles from Category 2 first for example, the categoryIndex would be 2 but on the dashboard it’s index would be 0 since it’s the only Category on there. So the categoryToUpdate would be undefined since it can’t find index 2 on the dashboard. I can’t think of a way to correctly grab the right object from the dashboard state in order to update my state to save my life. I thought about using categoryName to match my item but no idea how to use that to replace categories[categoryIndex].

Thank you in advance!!