How to drag and drop in between divs in reactjs?

I tried implementing drag and drop functionality in reactjs using vanilla HTML/js APIs. I almost completed it, but I cannot drop it between the existing divs. I want to add the functionality of dragging and dropping in both the divs (i.e., I should be able to drag any of the divs in the first column and drop anywhere in the second column and vice versa). So far, I am able to drag and drop only at the last index, not in between

Here is what I have tried so far. Please include the code. I am not that strong to follow if you are suggesting something

 <div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
      const App = () => {
        const drop = (e) => {
          e.preventDefault();
          const div_id = e.dataTransfer.getData("div_id");
          const block = document.getElementById(div_id);
          e.target.appendChild(block);
        };
        const dragOver1 = (e) => {
          e.preventDefault();
        };

        const dragStart = (e) => {
          const target = e.target;
          e.dataTransfer.setData("div_id", target.id);
        };

        const dragOver = (e) => {
          e.stopPropagation();
        };

        return (
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              padding: "50px",
            }}
          >
            <div
              onDrop={drop}
              onDragOver={dragOver1}
              id="board-1"
              style={{
                border: "1px solid #222",
                padding: 20,
              }}
            >
              <div
                id="firstfirst"
                draggable
                onDragStart={dragStart}
                onDragOver={dragOver}
              >
                <div>
                  <h1>First Column First Row</h1>
                </div>
              </div>
              <div
                id="firstsecond"
                draggable
                onDragStart={dragStart}
                onDragOver={dragOver}
              >
                <div>
                  <h1>First Column Second Row</h1>
                </div>
              </div>
              {Array.from(Array(2)).map((_, index) => {
                return (
                  <div
                    key={index}
                    id={`first${index}`}
                    draggable
                    onDragStart={dragStart}
                    onDragOver={dragOver}
                  >
                    <h1>First Column Row {index}</h1>
                  </div>
                );
              })}
            </div>
            <div
              id="board-2"
              onDrop={drop}
              onDragOver={dragOver1}
              style={{
                border: "1px solid #222",
                padding: 20,
              }}
            >
              <div
                id="secondfirst"
                draggable
                onDragStart={dragStart}
                onDragOver={dragOver}
              >
                <h1>Second Column First Row</h1>
              </div>
              <div
                id="secondsecond"
                draggable
                onDragStart={dragStart}
                onDragOver={dragOver}
              >
                <h1>Second Column Second Row</h1>
              </div>

              {Array.from(Array(2)).map((c, index) => {
                return (
                  <div
                    key={index}
                    id={`second${index}`}
                    draggable
                    onDragStart={dragStart}
                    onDragOver={dragOver}
                  >
                    <h1> Second Column Row {index} </h1>
                  </div>
                );
              })}
            </div>
          </div>
        );
      };
      ReactDOM.render(<App />, document.getElementById("app"));
    </script>

No routes matched location “/rewards-store”

I have a problem with the router V6. The routes are not being rendered. The homepage use to have all the products and now I cannot see any of the products shown, also I have my code to the links that go to every part of the website but is not appearing. The error that appears is:

react_devtools_backend.js:4045 No routes matched location "/rewards-store-andrea-lopez-bravo"  
    at Routes (http://localhost:3000/rewards-store-andrea-lopez-bravo/static/js/vendors~main.chunk.js:32538:5)
    at Router
    at div
    at App (http://localhost:3000/rewards-store-andrea-lopez-bravo/static/js/main.chunk.js:423:63)
    at Router (http://localhost:3000/rewards-store-andrea-lopez-bravo/static/js/vendors~main.chunk.js:32471:15)
    at BrowserRouter (http://localhost:3000/rewards-store-andrea-lopez-bravo/static/js/vendors~main.chunk.js:31958:5)
    at AppProvider (http://localhost:3000/rewards-store-andrea-lopez-bravo/static/js/main.chunk.js:4188:5)
index.tsx:25 No routes matched location "/rewards-store" 

This my router:

import { Routes, Route } from "react-router-dom";
import { Home } from "../pages/Home";
import { History } from "../pages/History";
import { Points } from "../pages/Points";
import { NotFound } from "../components/notification/NotFound";

 
 export const Router  = () => {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/history" element={<History/>}/>
      <Route path="points" element={<Points/>}/>
      <Route path="NotFound" element={<NotFound/>} />
    </Routes>
  );
};

This is index:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import AppProvider from "./context/AppContext";
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
    <AppProvider>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </AppProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

AppContext:

import React,{ useState } from "react";
 import { usePagination } from "../components/utils/pagination.jsx";


export const AppContext = React.createContext();


export default function AppProvider({ children }) {
    const [user,setUser] = useState({})
    const [points, setPoints] = useState(0)
    const [products, setProducts] = useState([])
    const [reedemStatus, setReedemStatus] = useState({})
    const [history, setHistory] = useState([])

    const paginationList = usePagination(products, 16)
    const paginationHistoryList = usePagination(history, 16)

    const totalProducts = products.length
    const totalHistory = history.length

    const handlerAddPoint =(value)=>{
        const newUser = {...user}
        newUser.points = user.points + value
        setUser(newUser)
      }
    
      const handlerSubtractPoint =(points)=>{
        const newUser = {...user}
        newUser.points = user.points - points
        setUser(newUser)
      }
    return(
        <AppContext.Provider value={{user,
            setUser,  
            handlerAddPoint, 
            handlerSubtractPoint, 
            points,
            setPoints,  
            products, 
            setProducts, 
            totalProducts,
            paginationList,
            reedemStatus, 
            setReedemStatus,
            history,
             setHistory, 
             paginationHistoryList,
             totalHistory}}>
             {children}
        </AppContext.Provider>
    );
}

App.js

import React, { useEffect, useContext } from "react";
import "./App.css";
import { Header } from "./components/header/Header";
import { Nav } from "./components/nav/Nav.jsx";
import { getUser } from "./services/users";
import { AppContext } from "./context/AppContext";
import { Notification } from "./components/notification/Notification";
import { Router } from "./routers/Router";

function App() {
  const { setUser } = useContext(AppContext);
  useEffect(() => {
    getUser().then((user) => {
      setUser(user);
    });
  }, [setUser]);
  return (
    <div className="App">
      <Notification />
      <Nav />
      <Header />
      <Router />
    </div>
  );
}

export default App;

The variable outside if else is not accessible in for loop [duplicate]

 function addSelected(clicked_id){
                    const ul = document.getElementById('sortable2');
                    const listItems = ul.getElementsByTagName('li');

                    if(clicked_id == "add1")
                    {
                      const pickNewUl = document.getElementById("slottable1");
                    }
                    else if(clicked_id == "add2")
                    {
                        const pickNewUl = document.getElementById("slottable2");
                    }
                  
                       
                    // Loop through the NodeList object.
                    for (let i = 0; i <= listItems.length - 1; i++) {
                        if(listItems[i].className=="selectedli")
                        {
                            console.log (listItems[i]); 
                            var createLi = document.createElement("li");
                            createLi.id = listItems[i].id;
                            createLi.innerHTML = listItems[i].textContent; 

                            pickNewUl.appendChild(createLi);


                           listItems[i].classList.remove('selectedli');
                      
                            }                                
                         }

                     }

Please check above code.

I am trying to copy selected li to a new ul list which is sucesfully done by the code above.

Issue is, I am not getting the value of “pickNewUl” in for loop outside of if else.

Created item is not deleting, JavaScript item lister project

I was creating a javascript item lister app, and i wanted to add delete item functionality. I am able to delete dummy items but the newly created items won’t delete.

Here’s the codepen: https://codepen.io/saabk/pen/eYGWarr

Here’s the HTML:

<!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">
  <link rel="stylesheet" href="style.css">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <title>DOM</title>
</head>

<body>
  <header id="main-header" class="bg-success text-white p-4 mb-3">
    <div class="container">
      <div class="row">
        <div class="col-md-6">
          <h1 id="header-title">Item Lister</h1>
        </div>
        <div class="col-md-6 align-self-center">
          <input type="text" class="form-control" id="filter" placeholder="Search items...">
        </div>
      </div>
    </div>
  </header>
  <div class="container my-4">
    <div class="card card-body" id="main">
      <h2 class="title">Add Items</h2>
      <form id="add-form" class="form-inline mb-3">
        <input id="inputItem" type="text" class="form-control mr-2">
        <input type="submit" class="btn btn-dark my-2" value="Submit">
      </form>
      <h2 class="title">Items</h2>
      <ul id="items" class="list-group">
        <li class="list-group-item">Item 1<button style="float: right;" class="btn btn-danger btn-sm delete">X</button>
        </li>
        <li class="list-group-item">Item 2<button style="float: right;" class="btn btn-danger btn-sm delete">X</button>
        </li>
        <li class="list-group-item">Item 3<button style="float: right;" class="btn btn-danger btn-sm delete">X</button>
        </li>
        <li class="list-group-item">Item 4<button style="float: right;" class="btn btn-danger btn-sm delete">X</button>
        </li>
      </ul>
    </div>
  </div>


  <script src="app.js"></script>
</body>

</html>

Here’s javascript code:

let form = document.querySelector('#add-form');
let itemsList = document.querySelector('#items');
let deleteButton = document.querySelectorAll('.delete');

form.addEventListener('submit', addItem);
deleteButton.forEach((item) => {
    item.addEventListener('click', deleteItem)
})

function addItem(e) {
    e.preventDefault();

    let newItem = document.querySelector('#inputItem');
    let itemText = document.createTextNode(newItem.value);
    
    let li = document.createElement('li');
    li.className = 'list-group-item';

    let delBtn = document.createElement('button');
    delBtn.className = 'btn btn-danger btn-sm delete';
    delBtn.textContent = 'X'
    delBtn.style.float = 'right';

    li.appendChild(itemText);
    li.appendChild(delBtn);
    itemsList.appendChild(li);
}

function deleteItem(e) {
    if(e.target.classList.contains('delete')) {
        if(confirm('Are you sure about that?')) {
            let li = e.target.parentElement;
            itemsList.removeChild(li);
        }
    }
}

The dummy items can be deleted but items created by the user won’t delete. Also i am using bootsrap. Please tell me how can i fix this issue.

Thank You!

Simultaneous filter in React?

I have 3 inputs for filtering.
searchByName
searchByColor
searchByCountry

How can i filter simultenously with 3 filter ? I can do this for 1 but ıcant with simulteneously

const data = [
  {
    name: "Jack",
    favoriteColor: "Green",
    country: "Germany",
  },
  {
    name: "Kane",
    favoriteColor: "Green",
    country: "Germany",
  },
  {
    name: "Hailey",
    favoriteColor: "Green",
    country: "France",
  },
];


data.map((res)=>{
  <h1> res.name </h1>
})

parametric func() selection in tag depending on argument parameter in html

I have an index.html running a menu

<a href='./satellites.html'> 
<a href='./simulation.html'>

The two files (satellites.html and simulation.html) are almost the same with the only difference in the function that is called when loaded

<!-- in the satellites.html-->
<body onload='init()'>            
...

and 
<!-- in the simulation.html-->
<body onload='initSimulation()'>  
...

Otherwise, the two HTML programs are identical.

Everything works fine but I want to avoid repeating the same code. How can the server control which function the client will call (using URL parameters probably)? I searched but it seems that the header is not available neither in HTML or in javascript.

Problem with using HTML form data in javascript functions

Recently I have been trying to change my code that took one HTML user input and used it in a javascript function. To do this I put the input into a query string and that worked fine. Then I tried to add another input. This is currently the form part of my code.

<form onsubmit="bazaartable()" class="pb-1">
    <div>
        <label>Please enter your tax rate here <i>(If not entered will use 1%)</i>:</label>
        <input type="text" id="taxRateForm" class="border border-cyan-500 rounded"/>
    </div>

    <div>
        <label><i>Enter unique amount here if needed</i>:</label>
        <input type="text" id="amountForm" class="border border-cyan-500 rounded"/>
    </div>
    
    <input type="submit" class="bg-cyan-500 py-1 px-1 rounded"/>
</form>

This is some of my javascript code including the function bazaartable.

<script>
    function takevalue1(){
        var taxRate = document.getElementById("taxRateForm").value;
        if (taxRate < 1){
                taxRate = 1
        }
        return taxRate
    }

    function takevalue2(){
        var amount = document.getElementById("amountForm").value;
        return amount
    }
    
    console.log(takevalue1())
    console.log(takevalue2())

    function bazaartable(){
    getbazaar = () => new Promise(a => getbazaar.data && !a(getbazaar.data) || fetch("https://api.hypixel.net/skyblock/bazaar").then(x => a(getbazaar.data = x.json())));
    document.getElementById("bazaar").innerHTML = arrayToTable([["Item Name", "Price x1 -0.1 Including Tax", "Price x64 -0.1 Including Tax", "x" + takevalue2()]], '<div class="row">{{content}}</div>', '<div class="column">{{content}}</div>');
    getbazaar().then(makeArray).then(x => arrayToTable(x, '<div class="row">{{content}}</div>', '<div class="column" title="{{content}}">{{content}}</div>')).then(x => document.getElementById("bazaar").innerHTML += x);
    }

    var iLikeThese = ["ENCHANTED_SNOW_BLOCK", "ENCHANTED_POTATO", "ENCHANTED_CARROT", "ENCHANTED_CLAY_BALL", "ENCHANTED_DIAMOND", "ENCHANTED_REDSTONE_BLOCK", "PACKED_ICE", "ICE"];
    
    function makeArray(data) {
        var arr = [];
        for (var i in data.products) {
            if (!iLikeThese.includes(i)) continue;
            var price = null;
            try {
                price = data.products[i].buy_summary[0].pricePerUnit
                price = price -= .1
                priceAfterTax = (price - (takevalue1()/100 * price))
            } catch (e) {}
            arr.push([i.replace(/_/g, " ").toLowerCase(), priceAfterTax.toFixed(1), (priceAfterTax*64).toFixed(1), (priceAfterTax*takevalue2()).toFixed(1)]);
        }
        return arr.sort((a, b) => a[0] > b[0] ? 1 : -1);
    }

    function arrayToTable(arr, row, column) {
        var result = "",
            substr = "";
        for (var i = 0; i < arr.length; i++) {
            substr = "";
            for (var j = 0; j < arr[i].length; j++) {
                substr += column.replace(/{{content}}/g, arr[i][j]);
            }
            result += row.replace(/{{content}}/g, substr);
        }
        return result;
    }
</script>

I have tried making takevalue1&2 return numbers but that and that works. The only thing that I can think of is that clicking the button clears the inputs before the function can read the values. If anyone can help please reply!

Foreach value insert to array

I have a Foreach data connected to a button.
I want to insert this foreach data into an array called myArray every time I click the button.
When I do myArray.push() , the data is added on top of each other.
3 data on the first click, 6 data on the second, 9 data on the 3rd…
However, I want that data to be updated, not pushed, so I want always 3 data, I just want their values to change, how can I do this?
Thanks.

// Foreach data
{
  "_id": "b94a22f5-acea-c649-d203-bdaa533c35b8",
  "productName": "Cookies",
  "productImage": "image://v1/6318fc_4f5a4c323cf74b21aaa61ddba1e924fb~mv2.jpg/file.jpg#originWidth=1050&originHeight=1050",
  "quantity": 4
}
{
  "_id": "dd7247dc-4f5f-a7fe-57df-20dce972fdc6",
  "productName": "Cake",
  "productImage": "image://v1/6318fc_c9a8011220064ddcb0bed049d1f6883d~mv2.jpg/file.jpg#originWidth=1200&originHeight=1800",
  "quantity": 3
}
{
  "_id": "ce5cae3b-db5a-623e-8c93-fec1c40c295d",
  "productName": "Coffee",
  "productImage": "image://v1/6318fc_4d19f3b393d94aa1aac03ab99b3abd8d~mv2.png/file.png#originWidth=833&originHeight=942",
  "quantity": 1
}


// I want it to be like this
console.log(myArray)
// output
// [
//   {
//   "_id": "b94a22f5-acea-c649-d203-bdaa533c35b8",
//   "productName": "Cookies",
//   "productImage": "image://v1/6318fc_4f5a4c323cf74b21aaa61ddba1e924fb~mv2.jpg/file.jpg#originWidth=1050&originHeight=1050",
//   "quantity": 4
// },
// {
//   "_id": "dd7247dc-4f5f-a7fe-57df-20dce972fdc6",
//   "productName": "Cake",
//   "productImage": "image://v1/6318fc_c9a8011220064ddcb0bed049d1f6883d~mv2.jpg/file.jpg#originWidth=1200&originHeight=1800",
//   "quantity": 3
// },
// {
//   "_id": "ce5cae3b-db5a-623e-8c93-fec1c40c295d",
//   "productName": "Coffee",
//   "productImage": "image://v1/6318fc_4d19f3b393d94aa1aac03ab99b3abd8d~mv2.png/file.png#originWidth=833&originHeight=942",
//   "quantity": 1
// }
// ]

Can not excess the value of a variable outside the class

i have this code where it will show the temperature of a place using Accuweather API. right now I have hardcoded newdelhi into it to find the weather condition of that place.but I want to know the weather by using the form. i am right know testing it with first name input form and trying to send that value in the location function. but I can’t use the input given by the user and use it outside the class. need help. i am new in react and appreciate if someone could help me with it. thank you

import React ,{useState,useEffect,state}from 'react';
import './App.css';
const apikey='zVp5GoY9fbwt8h4u5CvcWwneD1emnMMD';

const getcity = async(city) => {
    const base = 'http://dataservice.accuweather.com/locations/v1/cities/search';
    const query = `?apikey=${apikey}&q=${city}`;
  
    const response = await fetch(base + query);
    const data = await response.json();
  
    return data[0];
  }

  getcity('New Delhi')
  .then(data => {
    return getweather(data.Key);
  }).then(data =>{
    console.log(data);
  })
  .catch(err =>console.error(err));

  const getweather = async(id)=>{
  
    const base= 'http://dataservice.accuweather.com/currentconditions/v1/';
    const query =`${id}?apikey=${apikey}`;
  
    const response = await fetch(base + query)
    const data = await response.json();
  
    return data[0];
  }
  let newval = "initial value";
  console.log(newval)

export default class CustomerForm extends React.Component {

  
    
    
  constructor(props) {
    super(props);
    

    this.state = {
      customer: {
        firstName: props.firstName,
        lastName: props.lastName,
        status: props.status,
        
      }
    } 
  }

  handleFirstNameChanged(event) {
    var customer        = this.state.customer;
    customer.firstName  = event.target.value;

    this.setState({ customer: customer });
  }

  handleLastNameChanged(event) {
    var customer      = this.state.customer;
    customer.lastName = event.target.value;

    this.setState({ customer: customer });
  }

  handleStatusChanged(event) {
    var customer    = this.state.customer;
    customer.status = event.target.value;
    this.setState({ customer: customer });
  }
  
  
  handleButtonClicked() {
    console.log(this.state.customer);
    newval=this.state.customer.firstName;
    console.log(newval);
  }
  
  render() {
    return (
      <div>
        <label>
          First Name: 
        </label>
        <input type="text" value={this.state.customer.firstName} onChange={this.handleFirstNameChanged.bind(this)}/>
        <br/>
        <label>
          Last Name:
        </label>
        <input type="text" value={this.state.customer.lastName} onChange={this.handleLastNameChanged.bind(this)}/>
        <br/>
        <label>
          Status:
        </label>
        <select value={this.state.customer.status} onChange={this.handleStatusChanged.bind(this)}>
          <option value="PENDING">
            Pending
          </option>
          <option value="APPROVED">
            Approved
          </option>
        </select>
        <hr/>
        <button onClick={this.handleButtonClicked.bind(this)}>
          Save Record
        </button>
      </div>
    );
  }
}

Sending data from a Javascript program to a Python program and vice versa

I’m working on a project where data gathered from a Javascript program can be treated in a python program since many libraries in python are absent in Javascript. I’m currently trying to use Ajax to send the data between the .js file and the .py file

    $.ajax({
      type: "POST",
      url: "/Users/ryancheng/Desktop/coding/dashathon2021/dasha-app/webscrape.py",
      data: {param:restResult.data.features},
      success: function(response){
        output = response;
        alert(output);
      }
    }).done(function(data){
      console.log(data);
      alert(data);
    })

However I get the error ReferenceError: $ is not defined. Any help would be much appreciated. If there is any other method to send files back and forth that I am not aware of, please let me know.

how to insert array of data per column in MySQL?

I have arrays stacked in 1 array and I would like to insert each array per column in MySQL.
I have reached to insert all data in arrays to 1 column, but I want to insert an array per column.
Please see the screenshot and code below.

Image of array stack

con.connect(async(err)=>{
  const x = await getStock()
  if(err){
      console.log(err);
      return err;
  }else{
      console.log("DB ok");
  }
  console.log("connected");
  x.filter(item=>item===undefined?false:true).map(item=>item.forEach(item=>{
    const sql ="INSERT INTO test (testCol1) VALUES ?";
    const values=[
      [item]
    ];
    con.query(sql,[values],(err,result)=>{
      if(err)throw err;
      console.log("this have been recorded"+result);
    });
  }));
});

Javascrit .createTextNode output is giving errors

I created a website where it tells you your age. I use document.createTextNode to store the output but the output is not working properly. Here is the output code

var h1 = document.createElement("p");
h1.setAttribute("id", "mainText")
var mainText = document.createTextNode("You are ", ageYears, " years, ", ageMonths, " 
months and ", ageDays, " days old.");
h1.appendChild(mainText);
document.getElementById("new-age").appendChild(h1);

When I run my code, it only outputs the first part, “You are”. Is there any way to output the entire message.