Why am I getting the error message about each list item should get a unique key when using the react-bootstrap with Nextjs?

Here is the current setup of the file right now below. You will see that my file does indeed have a key to each child component but its still flagging it and I think its more internal issues that I am not sure that I can fix.

export default function SecondaryNav(props:NavItems) {

    const router = useRouter();
    let [filteredSubNavItems, setFilteredSubNavItems] = useState<{}[]>([])



/* Filtering the props.navigation array and setting the filteredSubNavItems state to the filtered
array. */
    useEffect(() => {
         props.navigation.filter((item) => {
            if(item.link == router.route) {
                setFilteredSubNavItems(item.subLinks);
            }
        })
    })


    return (
        <>
            <Navbar className={[styles.SecondaryNav].join(' ')}>
                    <div className={['container', styles.secondaryNavContainer].join(' ')}>
                                {
                                    filteredSubNavItems.map((navItem, index) => {
                                        return (
                                            <>
                                            {
                                                !navItem.subLinksExist ?
                                                    <Nav.Link key={navItem.name} href={navItem.link}>{navItem.name}</Nav.Link>
                                                 :
                                                    <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}>
                                                        {
                                                            navItem.sublinks.map((item) => {
                                                                return (
                                                                    <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item>
                                                                )
                                                            })
                                                        }
                                                    </NavDropdown>
                                            }
                                        </>
                                        )
                                    })
                                }
                    </div>
            </Navbar>
        </>
    )
}

And below is the file that I am pulling the data.

export const menuItems = [
    {
        primaryLink: 'Home',
        link: '/',
        subLinks: [
            {
                name: 'tutorial',
                subLinksExist: false,
                link: '/Home/Tutorial'
            },
            {
                name: 'contact',
                subLinksExist: false,
                link: '/Home/Contact'
            },
            {
                name: 'about',
                subLinksExist: false,
                link: '/Home/About'
            },
            {
                name: 'FAQ',
                subLinksExist: false,
                link: '/Home/Faq'
            },
            {
                name: 'version',
                subLinksExist: false,
                link: '/Home/Version'
            },
            {
                name: 'health check',
                subLinksExist: false,
                link: '/Home/Healthcheck'
            }
        ]
    },
    {
        primaryLink: 'Configuration',
        link: '/Configuration',
        subLinks: [
            {
                name: 'merchants',
                link: 'merchants',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'Billing Groups',
                        key: 'billing groups',
                        link: 'Configuration/Merchants/BillingGroup'
                    },
                    {
                        label: 'Billing Group Chain',
                        key: 'billing group chain',
                        link: 'Configuration/Merchants/BillingGroupChain'
                    },
                    {
                        label: 'Payment Channels',
                        key: 'payment channels',
                        link: 'Configuration/Merchants/PaymentChannels'
                    },
                    {
                        label: 'Relationship Managers',
                        key: 'relationship managers',
                        link: 'Configuration/Merchants/RelationshipManagers'
                    },
                    {
                        label: 'Fee Templates',
                        key: 'fee templates',
                        link: 'Configuration/Merchants/FeeTemplates'
                    },
                    {
                        label: 'Billing Group Disbursement Hold',
                        key: 'billing group disbursement hold',
                        link: 'Configuration/Merchants/BillingGroupDisbursementHold'
                    },
                ]
            },
            {
                name: 'partners',
                subLinksExist: false,
                link: 'Configuration/Partners'
            },
            {
                name: 'ODFIs',
                link: '/odfis',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'Bank Expenses',
                        key: 'bank expenses',
                        link: 'Configuration/ODFIs/BankExpenses'
                    },
                    {
                        label: 'Expense Batches',
                        key: 'expense batches',
                        link: 'Configuration/ODFIs/ExpenseBatches'
                    },
                    {
                        label: 'Routing Numbers',
                        key: 'routing numbers',
                        link: 'Configuration/ODFIs/RoutingNumbers'
                    },
                ]
            },
            {
                name: 'business units',
                link: '/businessunits',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'Support Contacts',
                        key: 'support contacts',
                        link: 'Configuration/BusinessUnits/SupportContacts'
                    }
                ]
            },
            {
                name: 'profile',
                link: '/profile',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'API Profiles',
                        key: 'api profiles',
                        link: 'Configuration/Profile/APIProfiles'
                    },
                    {
                        label: 'Heartland Users',
                        key: 'heartland users',
                        link: 'Configuration/Profile/HeartlandUsers'
                    },
                    {
                        label: 'External Users',
                        key: 'external users',
                        link: 'Configuration/Profile/ExternalUsers'
                    },
                ]
            },
            {
                name: 'system',
                subLinksExist: false,
                link: 'Configuration/System'
            }
        ]
    },
     {
        primaryLink: 'Support',
        link: '/Support',
        subLinks: [
            {
                name: 'automation',
                link: '/automation',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Alerts',
                        link: '/Support/Automation/Alerts'
                    },
                    {
                        label: 'Subscriptions',
                        link: '/Support/Automation/Subscriptions'
                    },
                    {
                        label: 'Jobs',
                        link: '/Support/Automation/Jobs'
                    },
                ]
            },
            {
                name: 'consumers',
                link: '/Consumers',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Blacklist',
                        link: '/Support/Consumers/Blacklist'
                    },
                    {
                        label: 'Whitelist',
                        link: '/Support/Consumers/Whitelist'
                    },
                    {
                        label: 'Provisional Whitelist',
                        link: '/Support/Consumers/ProvisionalWhitelist'
                    },
                ]
            },
            {
                name: 'invoices',
                link: '/Invoices',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Billing Group',
                        link: '/Support/Invoices/BillingGroup'
                    },
                    {
                        label: 'Partner',
                        link: '/Support/Invoices/Partner'
                    }
                ]
            },
            {
                name: 'logging',
                link: '/Logging',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Failed Api Calls',
                        link: '/Support/Logging/FailedApiCalls'
                    },
                    {
                        label: 'Logs',
                        link: '/Support/Logging/Logs'
                    },
                    {
                        label: 'Emails',
                        link: '/Support/Logging/Emails'
                    },
                ]
            },
            {
                name: 'ACH files',
                link: '/AchFiles',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'ACH Entry Finder',
                        link: '/Support/AchFiles/AchEntryFinder'
                    },
                    {
                        label: 'ACH Rejects',
                        link: '/Support/AchFiles/AchRejects'
                    }
                ]
            },
            {
                name: 'returns',
                link: '/Returns',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Return Files',
                        link: '/Support/Returns/ReturnFiles'
                    },
                    {
                        label: 'Return Details',
                        link: '/Support/Returns/ReturnDetails'
                    },
                    {
                        label: 'Exceptions',
                        link: '/Support/Returns/Exceptions'
                    },
                    {
                        label: 'Reinitiations',
                        link: '/Support/Returns/Reinitiations'
                    },
                    {
                        label: 'Notices Of Change',
                        link: '/Support/Returns/NoticeOfChange'
                    },
                    {
                        label: 'Return Reconciliations',
                        link: '/Support/Returns/ReturnReconciliations'
                    },
                ]
            },
            {
                name: 'bulwark',
                link: '/Bulwark',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Risk Rule Configuration',
                        link: '/Support/Bulwark/RiskRuleConfiguration'
                    },
                    {
                        label: 'Risk Rule Enforcement',
                        link: '/Support/Bulwark/RiskRuleEnforcement'
                    }
                ]
            }
        ]
     },
    {
        primaryLink: 'Terminal',
        link: '/Terminal',
        subLinks: [
            {
                name: 'virtual terminal',
                subLinksExist: false,
                link: '/VirtualTerminal'
            },
            {
                name: 'history log',
                subLinksExist: false,
                link: '/HistoryLog'
            }
        ]
    },
    {
        primaryLink: 'Sagacity',
        link: '/Sagacity',
        subLinks: [
            {
                name: 'management',
                link: '/Management',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Business Units',
                        link: '/Sagacity/Management/BusinessUnits'
                    },
                    {
                        label: 'Merchants',
                        link: '/Sagacity/Management/Merchants'
                    },
                    {
                        label: 'Users',
                        link: '/Sagacity/Management/Users'
                    },
                    {
                        label: 'Global',
                        link: '/Sagacity/Management/Global'
                    },
                    {
                        label: 'GIACT Invoices',
                        link: '/Sagacity/Management/GIACTInvoices'
                    },
                ]
            },
            {
                name: 'history',
                link: '/History',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Bank Accounts',
                        link: '/Sagacity/History/BankAccounts'
                    },
                    {
                        label: 'Consumers',
                        link: '/Sagacity/History/Consumers'
                    },
                    {
                        label: 'Verification Requests',
                        link: '/Sagacity/History/VerificationRequests'
                    },
                    {
                        label: 'Authentication Requests',
                        link: '/Sagacity/History/AuthenticationRequests'
                    },
                    {
                        label: 'Statics',
                        link: '/Sagacity/History/Statics'
                    },
                    {
                        label: 'Failed API Calls',
                        link: '/Sagacity/History/FailedApiCalls'
                    },
                ]
            }
        ]
    }
]

It is primarily flagging just the dropdown menus only. If you remove the dropdown components I dont get the error message.

Cannot work out how to access property of self in ViewModel

I am very new to js and html – trying to make a basic front end for a C# web api.

I’m making a simple app for tracking bugs. I have a panel for the list of bugs, where I can click “Details” to see more info on each bug (I would post an image, but my reputation is too low). Then a new panel opens with with the details of the bug, including a button to close the bug, ie change set the status to “closed”. It’s with this button that I have the problem.

I have this in my Index.cshtml:

 <div class="col-md-4">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h2 class="panel-title">Bugs</h2>
        </div>
        <div class="panel-body">
            <ul class="list-unstyled" data-bind="foreach: bugs">
                <li>
                    <strong><span data-bind="text: Title"></span></strong>: <span data-bind="text: Description"></span>
                    <small><a href="#" data-bind="click: $parent.getBugDetail">Details</a></small>
                </li>
            </ul>
        </div>
    </div>
    <div class="alert alert-danger" data-bind="visible: error"><p data-bind="text: error">
</p></div>

<!-- ko if:detail() -->
    @* Bug Detail with Close Button *@
    <div class="col-md-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h2 class="panel-title">Detail</h2>
            </div>
            <table class="table">
                <tr><td>Title</td><td data-bind="text: detail().Title"></td></tr>
                <tr><td>Description</td><td data-bind="text: detail().Description"></td></tr>
                <tr><td>Status</td><td data-bind="text: detail().Status"></td></tr>
                <tr><td>Created</td><td data-bind="text: detail().Created"></td></tr>
                <tr><td>Owner</td><td data-bind="text: detail().Owner"></td></tr>
            </table>
            <div class="panel-body">
                <form class="form-horizontal" data-bind="submit: closeBug(detail())">
                    <button type="submit" class="btn btn-default">Close bug</button>
                </form>
            </div>
        </div>
    </div>

    <!-- /ko -->

Then this is the relevant stuff in app.js:

var ViewModel = function () {
    var self = this;

    self.bugs = ko.observableArray();
    self.error = ko.observable();
    self.detail = ko.observable();

    self.getBugDetail = function (item) {
        ajaxHelper(bugsUri + item.Id, 'GET').done(function (data) {
            self.detail(data);
        });
    }

    var bugsUri = '/api/bugs/';

    function ajaxHelper(uri, method, data) {
        self.error(''); // Clear error message
        return $.ajax({
            type: method,
            url: uri,
            dataType: 'json',
            contentType: 'application/json',
            data: data ? JSON.stringify(data) : null
        }).fail(function (jqXHR, textStatus, errorThrown) {
            self.error(errorThrown);
        });
    }

    // get open bugs
    function getAllBugs() {
        ajaxHelper(bugsUri, 'GET').done(function (data) {
            self.bugs(data);
        });
    }

    // Fetch the initial data.
    getAllBugs();

    //close bug
    self.closeBug = function (localDetail) {

        var closedBug = {
            OwnerId: self.localDetail.OwnerId,
            Description: self.localDetail.Description,
            Status: "closed",
            Title: self.localDetail.Title,
            Created: self.localDetail.Created
        };

        ajaxHelper(bugsUri + self.localDetail.Id, 'DELETE', self.localDetail.Id);

        ajaxHelper(bugsUri, 'POST', closedBug).done(function (item) {
            self.bugs.push(item);
        });
    }

};

To update the status of a bug, I want to take the Id of the bug currently open in the detail panel and create an identical bug except with Status set to “closed”. The trouble is that there’s always a problem access self.localDetail in the new variable closedBug. I’ve tried it here by parameterizing the closeBug method, but I’ve also tried accessing self.Detail, but it’s done no good, so I’m here. My next step, if this fails, is to create a separate panel entirely with a form for bugId which closes the bug when you submit, but it would be better to be in the bug details window.

Bizarre case of one change making canvas event not listen

I started re-writing Windows!
The code below draws 10 canvas objects you can move around. I made them random sizes.
When you click on one it has thicker outline and can be dragged around.

When I added one line to change the initial top position of the canvases the move stopped working.
Its very odd, I only wanted to stack the windows in increasing 10px steps rather then them all starting at the same spot.
Why could this minor change stop the rest working?

var n = 0,
  canv = [],
  ct = []
var body = document.getElementsByTagName("body")[0];
var targ, wind = 10,
  i, offx, offy = 0
for (n = 0; n < wind; n++) {
  canv[n] = document.createElement('canvas');
  canv[n].id = "C" + n;
  canv[n].width = rnd(30 * n);
  canv[n].height = rnd(30 * n);
  //canv[n].style.top=10*n     <- This line stops the drag effect working
  canv[n].style.zIndex = n;
  canv[n].style.position = "absolute";
  canv[n].style.border = "2px solid";

  body.appendChild(canv[n]);
  ct[n] = canv[n].getContext("2d");
  ct[n].fillText(n, canv[n].width / 2, canv[n].height / 2)

  canv[n].addEventListener('mousedown', function(e) {
    targ = e.currentTarget
    if (targ.style.border == "2px solid") {
      for (i = 0; i < wind; i++) {
        canv[i].style.border = "2px solid"
      }
      targ.style.border = "5px solid";
      offy = e.y - targ.style.top
    } else {
      targ.style.border = "2px solid"
    }
  });
  canv[n].addEventListener('mousemove', function(e) {
    if (targ.style.border == "5px solid") {
      move(e.x, e.y)
    }
  });
}

function move(x, y) {
  targ.style.top = y - offy
}

function rnd(m) {
  return Math.floor(Math.random() * m)
}

How to prompt a Screen before going into Navigation Root in React Native?

I am in my AppRoot and am trying to implement a subscription paywall screen, that will be prompted when the loading of the app is done if the user is not subscribed, but will continue with the regular flow if the user is subscribed. Here is the return of my approot currently.

return (
        <SettingsProvider>
            { ({ isLoading }) => (
                (isLoading || !isLoadingComplete) ? (
                    <KeepSplashScreen/>
                ) : (
                    <PaperProvider theme={theme}>
                        <SafeAreaProvider>
                            /// prompt subscription screen here??
                            <NavigationRoot />
                        </SafeAreaProvider>
                    </PaperProvider>
                )
            )}
        </SettingsProvider>
    );

I was thinking of using a navigation stack or something similar to show the screen here based on a status such as

const status = true

What would be the best route to approach this?

I’ve tried putting in a stack

 <Stack.Screen
                        name="Subscreen"
                        component={SubScreen}
                        initialParams={{ initialroute: 'Home' }}
                    />

But I’m not sure if this is the way to do it?

data doesn’t update with dependancy?

i have a page that shows a list of ingredients. And it works fine when online.
i tried adding an offline feature that i can show the list (get) in offline mode.
But if i add any condition in useEffect the dependancy doens’t work and doesn’t update the data directly.
And i need to refresh the page manually or type something to see the new inserted or edited data. This doesn’t apply for DELETE because that is working fine

i have a page that shows a list of ingredients. And it works fine when online.
i tried adding an offline feature that i can show the list (get) in offline mode.
But if i add any condition in useEffect the dependancy doens’t work and doesn’t update the data directly.
And i need to refresh the page manually or type something to see the new inserted or edited data. This doesn’t apply for DELETE because that is working fine. i’m a new with react.

`

`import React, { useState, useEffect, cloneElement } from 'react';
import '../styles/ShoppingList.css';
import {
  getDoc,
  doc,
  addDoc,
  collection,
  getDocs,
  query,
  where,
  updateDoc,
  deleteDoc,
} from 'firebase/firestore';
import { auth, firestore } from '../firebase';
import ReadItem from '../components/ShoppingList/ReadItem';
import Edit from '../components/ShoppingList/Edit';
import axios from 'axios';
import { Autocomplete, TextField } from '@mui/material';
import { async } from '@firebase/util';

const ShoppingList = () => {
  const [todo, setTodo] = useState('');
  const [todos, setTodos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editValueKey, setEditValueKey] = useState('');
  const [SelectTodos, setSelectTodos] = useState([]);
  const [Previoustodo, setPreviousTodo] = useState('');
  const [LocalData, SetLocalData] = useState([]);

  const AutoComplete = async () => {
    axios
      .get(
        //a8034eddd0924996955f2838890b9761 
        //fa7d10c9b49249268540fcd39db9283b
        //075d827095ae4832835c9c0b0d282448
        'https://api.spoonacular.com/food/ingredients/search?apiKey=9ce5ee89a5f14a4dbbfa42aa09d87e9b&timeFrame=day?number=4&query=' +
          todo
      )
      .then((res) => {
        const dataOptions = res.data.results.map(({ id, name }) => ({
          label: name,
          value: id,
        }));
        setSelectTodos(dataOptions);
        console.log(SelectTodos);
      });
  };

  const geTodos = async () => {
    const datalijst = [];
try{  const userSnapshot = await getDocs(
  query(
    collection(firestore, 'groceries'),
    where('uidd', '==', auth.currentUser?.uid)  
  )
  
)
SetLocalData(userSnapshot);
}
catch {
  console.log(localStorage.getItem('DataLijst'))
}
 
    console.log('snapshot opgehaald');
    LocalData.forEach((doc) => {
      const data = doc.data();
      console.log(data.todo);
      datalijst.push({
        ...doc.data(), //spread operator
        key: doc.id, // `id` given to us by Firebase
      });
    });
    setTodos(datalijst);
    localStorage.setItem('DataLijst', datalijst);
    setLoading(false);
    console.log(datalijst);
  };

  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      console.log(todo);
      AutoComplete();
      console.log('LOGGED IN');
      geTodos();
      if (!user) {
        console.log('no user logged in');
      }
    });
  }, [loading, todo ]);

  const writeToDatabase = (label, value) => {
    addDoc(collection(firestore, 'groceries'), {
      todo: label,
      todoid: value,
      uidd: auth.currentUser?.uid,
    });
    setTodo('');
  };

  const handleEditClick = (event, todo) => {
    console.log('edit', todo);
    event.preventDefault();
    setEditValueKey(todo?.key);
  };

  const updateUser = async (key, todoLabel, todoValue) => {
    console.log('key', key, todoValue);
    const userDoc = doc(firestore, 'groceries', key);
    const newFields = { todo: todoLabel, todoid: todoValue };
    await updateDoc(userDoc, newFields);
    const index1 = todos.findIndex((todo) => todo?.key === key);
    todos[index1] = { label: todoLabel, value: todoValue };
    setEditValueKey(null);
  };

  const DeleteTodo = async (key) => {
    console.log('key', key);
    const userDoc = doc(firestore, 'groceries', key);
    await deleteDoc(userDoc);
    const index1 = todos.findIndex((todo) => todo?.key === key);
    setTodos((prev) => prev.filter((el) => el?.key !== todos[index1]?.key));
  };

  const HandleSelect = (event, value) => {
    console.log('select', value);
    event.preventDefault();
    setTodo(value);
    writeToDatabase(value.label, value.value);
    setTodo('');
  };

  const HandleEditSelect = (event, value) => {
    console.log('select');
    event.preventDefault();
    setTodo(value);
    updateUser(Previoustodo.key, value.label, value.value);
  };

  if (loading) {
    return <h1>loading firebase data...</h1>;
  }

  return (
    <div className="IngredientPage">
      <h1>Ingredient List</h1>

      <div className="IngredientList">
        <div className="AutoComplete">
          <Autocomplete
            disablePortal
            id="combo-box-demo"
            options={SelectTodos}
            onChange={HandleSelect}
            className="SearchBar"
            sx={{ width: 300 }}
            renderInput={(params) => (
              <TextField
                {...params}
                label="Ingredient"
                onChange={(e) => setTodo(e.target.value)}
              />
            )}
          />
        </div>

        <div className="IngredientContainer">
          {todos?.map((todo) =>
            editValueKey === todo?.key ? (
              <div>
                <Edit
                  SelectTodos={SelectTodos}
                  setPreviousTodo={setPreviousTodo}
                  setTodo={setTodo}
                  todo={todo}
                  HandleEditSelect={HandleEditSelect}
                />
              </div>
            ) : (
              <div>
                <ReadItem
                  todo={todo}
                  handleEditClick={handleEditClick}
                  DeleteTodo={DeleteTodo}
                />
              </div>
            )
          )}
        </div>
      </div>
    </div>
  );
};
export default ShoppingList;`

`

filtering table rows based on multiple select fields

My project
I’ve been working on a small project to try and get a table that you can filter using 2 select boxes.

I’ve used some code I found on a similar question here and tried modifying it. The first select box works perfectly but I can’t seem to get the second to work.

Any help would be really appreciated.

The Code

<!doctype html>
<html><head>
<script>
function searchTable() {
    var input, filter, inputtwo, filtertwo, found, table, tr, td, i, j;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    inputtwo = document.getElementById("myInput2");
    filtertwo = inputtwo.value.toUpperCase();
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        for (j = 0; j < td.length; j++) {
            if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                found = true;
            }
        }
        if (found) {
            tr[i].style.display = "";
            found = false;
        } else {
            if (tr[i].id != 'tableHeader'){tr[i].style.display = "none";}
        }
    }
}
</script>
<meta charset="utf-8">
<title>Filtered Table</title>
<style type="text/css">
#myInput {
  width: 100%; /* Full-width */
  font-size: 16px; /* Increase font-size */
  padding: 12px 20px 12px 40px; /* Add some padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input */
}
#myInput2 {
  background-image: url('/css/searchicon.png'); /* Add a search icon to input */
  background-position: 10px 12px; /* Position the search icon */
  background-repeat: no-repeat; /* Do not repeat the icon image */
  width: 100%; /* Full-width */
  font-size: 16px; /* Increase font-size */
  padding: 12px 20px 12px 40px; /* Add some padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input */
}
#myTable {
  border-collapse: collapse; /* Collapse borders */
  width: 100%; /* Full-width */
  border: 1px solid #ddd; /* Add a grey border */
  font-size: 18px; /* Increase font-size */
}

#myTable th, #myTable td {
  text-align: left; /* Left-align text */
  padding: 12px; /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}
#name {
        display:none;
    }
</style>
</head>

<body>
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tbody>
        <tr>
          <td width="50%"><select id="myInput" onchange="searchTable()" placeholder="Role Category..">
              <option disabled selected value> -- select an option -- </option>
    <option value="Leadership">Leadership</option>
    <option value="Infrastructure">Infrastructure</option>
              </select>
            </td>
          <td width="50%"><select id="myInput2" onchange="searchTable()" placeholder="Role Category..">
              <option disabled selected value> -- select an option -- </option>
    <option value="London">London</option>
    <option value="South East">South East</option>
              </select>
          </td>
        </tr>
      </tbody>
</table>
<table id="myTable">
  <tr id="tableHeader" class="header">
    <th style="width:60%;"><span style="width:40%;">Role Category</span></th>
    <th style="width:40%;">Role</th>
    <th style="width:40%;">Region</th>
    <th style="width:40%;">Lower Quartile</th>
    <th style="width:40%;">Median</th>
    <th style="width:40%;">Upper quartle</th>
  </tr>
  <tr>
    <td>Leadership</td>
    <td>Chief Technology Officer </td>
    <td>London</td>
    <td>£100,000</td>
    <td>£145,000</td>
    <td>£185,000</td>
  </tr>
  <tr>
    <td>Leadership</td>
    <td>Chief Information Officer </td>
    <td>London</td>
    <td>£100,000</td>
    <td>£135,000</td>
    <td>£180,000</td>
  </tr>
  <tr>
    <td>Leadership</td>
    <td>Chief Information Security Officer </td>
    <td>London</td>
    <td>£95,000</td>
    <td>£140,000</td>
    <td>£180,000</td>
  </tr>
  <tr>
    <td>Leadership</td>
    <td>Chief Technology Officer </td>
    <td>South East</td>
    <td>£92,593 </td>
    <td>£134,259</td>
    <td>£171,296</td>
  </tr>
  <tr>
    <td>Leadership</td>
    <td>Chief Information Officer </td>


    <td>South East</td>
    <td>£92,593 </td>
    <td>£125,000</td>
    <td>£166,667</td>
  </tr>
  <tr>
    <td>Leadership</td>
    <td>Chief Information Security Officer </td>
    <td>South East</td>
    <td>£87,963</td>
    <td>£129,630</td>
    <td>£166,667</td>
  </tr>
  <tr>
    <td>Infrastructure</td>
    <td>Chief Technology Officer </td>
    <td>London</td>
    <td>£100,000</td>
    <td>£145,000</td>
    <td>£185,000</td>
  </tr>
  <tr>
    <td>Infrastructure</td>
    <td>Chief Information Officer </td>
    <td>London</td>
    <td>£100,000</td>
    <td>£135,000</td>
    <td>£180,000</td>
  </tr>
  <tr>
    <td>Infrastructure</td>
    <td>Chief Information Security Officer </td>
    <td>London</td>
    <td>£95,000</td>
    <td>£140,000</td>
    <td>£180,000</td>
  </tr>
  <tr>
    <td>Infrastructure</td>
    <td>Chief Technology Officer </td>
    <td>South East</td>
    <td>£92,593 </td>
    <td>£134,259</td>
    <td>£171,296</td>
  </tr>
  <tr>
    <td>Infrastructure</td>
    <td>Chief Information Officer </td>
    <td>South East</td>
    <td>£92,593 </td>
    <td>£125,000</td>
    <td>£166,667</td>
  </tr>
  <tr>
    <td>Infrastructure</td>
    <td>Chief Information Security Officer </td>
    <td>South East</td>
    <td>£87,963</td>
    <td>£129,630</td>
    <td>£166,667</td>
  </tr>
</table>
</body>
</html>

Javascript (vanilla) drag and drop does not work the second time an element is dragged and dropped

I am trying to implement a drag and drop functionality using vanilla Javascript on my web app, where element gets moved to a new position within a div, once it’s dragged and dropped.

But I am having an issue where I can drop the element fine the first time, but I can no longer do it the second time onwards.

After debugging, I have noticed that the first time I drop an element, it does not have any inline style (see Appendix A). But when I try and do it the second time, it now has an inline style (see Appendix B) and for some reason, I cannot chnage the values of it. That was also the case after I manually added inline style to my draggable element- I could not drop the item even the first time when I did it.

I am completely out of ideas as to what I could be doing wrong and no similar questions yielded a solution.

Thank you very much in advance for your time.

Code (Unnecessary parts ommitted)

HTML:

<div id="list" ondrop="dropItem(event)" ondragover="dragOver(event)">
    <div id="test" draggable="true" ondragstart="dragStart(event)">
        <button type="button"></button>
            <div>
                <p>Test</p>
            </div>
    </div>
</div>

CSS:

#list
{
    position: relative;
    top: 60px;
    height: 600px;
    width: 100%;
    border: 2px solid rgb(107, 14, 14);
    display: block;
}

#list > div
{
    position: absolute;
    height: 200px;
    width: 200px;
    background-color: blue;
    margin: 10px;
    overflow: hidden;
    text-align: left;
}

JS:

const list = document.querySelector("#list");
const rect = list.getBoundingClientRect();
let oldLeft, oldTop, mouseXStart, mouseYStart;

function dragStart(event)
{
    event.dataTransfer.setData("plain/text", event.target.id);
    const item = document.querySelector("#" + event.target.id);

    mouseXStart = event.clientX - rect.left;
    mouseYStart = event.clientY - rect.top;
    oldLeft = item.style.left;
    oldTop = item.style.top;

    console.log(item);
}

function dragOver(event)
{
    event.preventDefault();
    event.dataTransfer.dropEffect = "move";
}

function dropItem(event)
{
    event.preventDefault();
    const mouseXEnd = event.clientX - rect.left;
    const mouseYEnd = event.clientY - rect.top;
    //Calculate by how much mouse has been moved
    const newLeft = mouseXEnd - mouseXStart;
    const newTop = mouseYEnd - mouseYStart;
    const item = document.querySelector('#' + event.dataTransfer.getData("plain/text"));

    item.style.left = oldLeft + newLeft + "px";
    item.style.top = oldTop + newTop + "px";
}

Appendix A

console.log() output on the first dragStart() call:

<div id="test" draggable="true" ondragstart="dragStart(event)">

Appendix B

console.log() output on the second dragStart() call:

<div id="test" draggable="true" ondragstart="dragStart(event)" style="left: 853px; top: 147px;">

Changing value of input range not updating content on mobile

I have an HTML input range that uses JS to change the text content of a table below it based on the value of the input range. It is working on Desktop but on Mobile the content will be stuck at the specified content for value = 1 and won’t change to 2, 3, and 4. Any ideas? Thank you!

<div class="range-wrap">
          <input type="range" class="range" id="slide" value="1" min="1" max="4" />
        <output class="bubble"></output>
        </div>
<h3 class="you-will">Every week you will save...</h3>
<table class="save">
  <tr>
    <td><img class="eco-icon" src="https://www.happynest.com/hubfs/14500231/eco-icons-01.png" alt="time" / ></td>
    <td class="eco-text"><strong><span id="time"></span></strong> <span>Spend time outdoors!</span></td>
  </tr>
  <tr>
    <td><img class="eco-icon" src="https://www.happynest.com/hubfs/14500231/eco-icons-02.png" alt="water" / ></td>
    <td class="eco-text"><strong><span id="water"></span></strong> <span>Save the environment.</span></td>
  </tr>
  <tr>
    <td><img class="eco-icon" src="https://www.happynest.com/hubfs/14500231/eco-icons-03.png" alt="electricity" / ></td>
    <td class="eco-text"><strong><span id="electric"></span></strong> <span>Save some money.</span></td>
  </tr>
</table>

JS

function updateSlider() {
    var value = $("#slide").val();
    if (value == 1) {
      $("#time").text("4 hours of time.");       
      $("#water").text("60 gallons of water.");
      $("#electric").text("$5 in electric bills.");
    } else if (value == 2) {
       $("#time").text("8 hours of time.");       
      $("#water").text("120 gallons of water.");
      $("#electric").text("$10 in electric bills.");
    } else if (value == 3) { 
       $("#time").text("12 hours of time.");       
      $("#water").text("180 gallons of water.");
      $("#electric").text("$15 in electric bills.");
    } else if (value == 4) {
       $("#time").text("16 hours of time.");       
      $("#water").text("240 gallons of water.");
      $("#electric").text("$20 in electric bills.");
    }
}

updateSlider();
$('#slide').mousemove(updateSlider);

const allRanges = document.querySelectorAll(".range-wrap");
allRanges.forEach(wrap => {
  const range = wrap.querySelector(".range");
  const bubble = wrap.querySelector(".bubble");
  range.addEventListener("input", () => {
    setBubble(range, bubble);
  });
  setBubble(range, bubble);
});

function setBubble(range, bubble) {
  const val = range.value;
  const min = range.min ? range.min : 0;
  const max = range.max ? range.max : 100;
  const newVal = Number(((val - min) * 100) / (max - min));
  bubble.innerHTML = val;
  // Sorta magic numbers based on size of the native UI thumb
  bubble.style.left = `calc(${newVal}% + (${8 - newVal * 1.5}px))`;
}

The input range is changing the table’s content on Desktop but not mobile

How to find and replace two different string in double quotes?

I have this string

Expected "contains text 'asdr.js'" but got: "does not contain 'asdr.js'" (2s)

I wanted to replace the double quotes string, like this

Expected <span class="green-color-text">"contains text 'asdr.js'"</span> but got: <span class="red-color-text">"does not contain 'asdr.js'"</span> (2s)

I tried using the regex solution available in StackOverflow, but none of it worked for me.

Event handling on dynamic canvas

… an array of canvas elements.
I dont really understand the (e) argument, and how to pass which canvas was clicked to the move function.
This simple demo draws canvas elements, and I want the one that is clicked to move down.
do I need to use .this as the e ???

<script>
var n=0, canv=[], ct=[]
var body = document.getElementsByTagName("body")[0];
var t=0
for (n=0; n<10; n++){ // create 10 canvas
 canv[n] = document.createElement('canvas');
 canv[n].id = "C"+n;
 canv[n].width = rnd(300);
 canv[n].height = rnd(300);
 canv[n].style.zIndex = n;
 canv[n].style.position = "absolute";
 canv[n].style.border = "2px solid";

body.appendChild(canv[n]);
ct[n] = canv[n].getContext("2d");

canv[n].addEventListener('mousedown', function (e) {
    move(n)
});

}

function move(num){
 t++
 canv[num].style.top=t
}

function rnd(m){return Math.floor(Math.random()*m)}
</script>
</body>

How can I pass search bar results to render on home component?

It’s my first time making an app that has a search feature with api and I couldn’t find a way to render the search results from the search bar in the header component to home component or any other, so when the user search for something, no matter what’s the location the results should render on screen instead of the actual current component’s data but for now home screen is fine, since if I find a solution for this, the rest would be easy.

header:

function Header() {
  const userLogin = useSelector((state) => state.userLogin);
  const { userInfo } = userLogin;
  const [items, setItems] = useState("");
  const debounce = useDebounce(items, 500);
  const dispatch = useDispatch();
  const logoutHandler = () => {
    dispatch(logout());
  };

  useEffect(() => {
    const getData = setTimeout(() => {
      axios.get(`/api/search/?search=${items}`).then((response) => {
        console.log(response.data[0]);
      });
    }, 2000);

    return () => clearTimeout(getData);
  }, [debounce]);
  return (
    <div>
      <Navbar bg="dark" variant="dark" className="navCustom">
        <Container>
          <LinkContainer to="/">
            <Navbar.Brand>eCommerce</Navbar.Brand>
          </LinkContainer>
          <Form className="d-flex">
            <Form.Control
              type="search"
              placeholder="Search"
              className="me-2"
              aria-label="Search"
              onChange={(e) => {
                setItems(e.target.value);
              }}
            />
            <Button variant="outline-success">Search</Button>
          </Form>

home:

import React, { useEffect } from "react";
//import products from "../../products";
import { Row, Col } from "react-bootstrap";
import Product from "../Product";
import { useDispatch, useSelector } from "react-redux";
import { listProducts } from "../../actions/ProductAction";
import Message from "../Message";
import Loader from "../Loader";

function HomeScreen() {
  const dispatch = useDispatch();
  const productList = useSelector((state) => state.productList);
  const { error, loading, products } = productList;
  useEffect(() => {
    dispatch(listProducts());
  }, [dispatch]);

  return (
    <div>
      <h1 className="text-center">Latest Products</h1>
      {loading ? (
        <Loader />
      ) : error ? (
        <Message variant="danger">{error}</Message>
      ) : (
        <Row>
          {products &&
            products.map((product) => (
              <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                {/* <h3>{product.name}</h3> */}
                <Product product={product} />
              </Col>
            ))}
        </Row>
      )}
    </div>
  );
}

export default HomeScreen;