How to add onClick to button as contentEditable div inner contents

I am using react-contentEditable package from npm. When my user clicks a contact, I want to show a nice label, name, and also a button to remove this label from the editable div if the user wants.

I have the label and name figured out, but I cant seem to understand how to pass the onClick to a button when it is rendered like this below

`<label contentEditable="false" class="p-1 rounded-capsule">${contact.firstName + " " + contact.lastName + " "}<span class="badge fs--1 badge-soft-success badge-pill ml-2">${contact.phone_number}</span><button class="badge-pill badge-soft-primary">X</button></label>`)) // How do I pass an onClick to the button?

Here is the full component

import React, { useState, useRef, useEffect, Fragment } from 'react';
import ContentEditable from 'react-contenteditable';


const [toField, setToField] = useState({value: " ", html: " "})
const toFieldRef = useRef()

const addContactsToDiv = () => {
    let selectedContactsArray = [] // create and empty array
    const Matches = selectedRows.filter((row) => {
      const isMatched = contacts.some(contact => { if(contact._id == row) {
        selectedContactsArray.push({firstName: contact.firstName, lastName: contact.lastName, phone_number:contact.phone_number, _id: contact._id})
      }})
      return isMatched
    })
    const matchedContactsArray = []
    selectedContactsArray.map(contact => { // mapping over selected to add html 

// How can I add an onClick to the button when I have to pass it as string?
      matchedContactsArray.push((`<label contentEditable="false" class="p-1 font-weight-bold bg-primary ml-2 text-white rounded-capsule shadow-none fs--3">${contact.firstName + " " + contact.lastName + " "}<span class="badge fs--1 badge-soft-success badge-pill ml-2">${contact.phone_number}</span><button class="badge-pill badge-soft-primary">X</button><span name="indy-contacts" class="d-none">${contact._id}</span></label>`))
    })
    matchedContactsArray.map(contact => { return contact})
     const stringifiedRows = matchedContactsArray.toString() // push stringified results in to array
     setToField({...toField, html: stringifiedRows}) // update state with array instead of updating state inside loop
    
  }

 <ContentEditable
         name="to"
         innerRef={toFieldRef} // passing our ref instead of state
         html={toField.html} // the html = our ref.current property
         //value={toField}
         onBlur={handleBlur}
         onClick={() => {handleClick()}}
         onChange={handleChange} // this sets our refs.current = event.target.value
         style={{minHeight: "7em", maxHeight: "10em", overflow: "auto"}}
         className="border border-2x border-300 bg-light rounded-soft fs-1"
         >
         </ContentEditable>

TypeScript object type casting, when the two objects differ by key name(s)

This might have been asked before, but I have a situation where I have an object type which my backend expects like so:

type TagTypeThatMyBackendWants = {
    id: string;
    name: string;
}

It consist of two string type keys, the key names being id and name. I get these type of Tag-objects from my backend and my backend also expects objects like these back. Now, the problem is that I am using a library that handles these tags, but the library expects the objects to look like this:

type TagTypeThatALibraryWants = {
    id: string;
    text: string;
}

So it is basically the same object, but instead of a name key with a type of string, the library expects a text key with a type of string. I kind of already solved this by doing some custom mapping back and forth, but this raised the question if there is an “official” or a recommended way to do something like this – like casting from one object type to another, with the ability to tell TypeScript that the name-key “maps” to text-key and vice versa.

Hwo to update/delete ref value in VueJS 3 composition api

Im using a ref value to be able to only execute a click event if the ref value is changing

for example if I want to update/del the array inside let myRef = ref([]);
do i just drill inside the proxy and do the operations
like

 selectedElements.value.push(3);

which returns
Proxy {0: 3}

or what is the correct way to update/del the ref.value ?

export default {  
  setup() {
    let myRef   = ref([]);
  
    return {
     myRef
    };
  },
};
</script>

javascript change value but inside onchange event listener not firing

I wrote a simple script to count words while typing in form
My question is why by changing the value of the word_count field when typing;
The EventListener of word_count is not fired

document.getElementById('subject').addEventListener('change', function() {
    var string = this.value
    string = string.replace(/s+/g, " ");
    var words = string.split(/s+/).length;
    document.getElementById('word_count').value = words;
}, false);
document.getElementById('subject').addEventListener('keypress', function() {
    var string = this.value
    string = string.replace(/s+/g, " ");
    var words = string.split(/s+/).length;
    document.getElementById('word_count').value = words;
}, false);
document.getElementById('word_count').addEventListener('change', function() {
    alert('change fired');
}, false);  
<form>
   <div> <label for="story">string:</label>
      <textarea   id="subject" name="subject"></textarea>
   </div>
   <div>  <label for="story">count:</label>
      <input id="word_count">
   </div>
</form>

how to use length-limit on RegExp Object with JavaScript?

const ipv6="([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+)";
const regex = new RegExp(ipv6);
const result = SAMPLE_STRING.match(regex);
console.log(result);

run code result is

SyntaxError: Invalid regular expression: /([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+)/: Nothing to repeat

The ‘ipv6’ works with a regex-compiler, but not with javascript.

And i must use the ‘new Regex’ object.
how can i make the work?

How to implement Tap To Focus for camera in JavaScript?

I’m working on a web application that has a custom camera screen, for which I’m supposed to implement tap to focus using getUserMedia

Here’s the code:

 const permissionConstraints = {
       video: { 
       width: { exact: 1280 }, height: { exact: 1280 },
       aspectRatio: { ideal: 1 }, facingMode: 'environment' }
 };

 navigator.mediaDevices.getUserMedia(permissionConstraints).then((permissionsObj) => {
        console.log(permissionsObj);
 })

How to wait for an object to be asynchronously edited?

I have an array of items where I want to append an async value getProductMinQuantity.

The problem is that the render res.status(200)... is sent before item.order_quantity_minimum had been edited.

I thought that a map like below would create a new promise with the items updated.

newResult is a type Promise<any>[] | undefined, I cannot do .then .catch to then execut my res.status in it.

const getCart = async () => {
  
  ...

  let newResult = result.data?.line_items.physical_items.map(async (item: any) =>
    item.order_quantity_minimum = await getProductMinQuantity(item.product_id)
  )

  res.status(200).json({
    data: result.data ? normalizeCart(result.data) : null,
  })
}

Any thought how I can arrange that ?

Why is event.target.files[0].name showing error in my code?

I have this JS code (given below) which converts a JSON file to XML file. Everything works perfectly (I get the contents of the file), but now I want to fetch the filename of the uploaded file.

function onChange(event) {
        var reader = new FileReader();
        reader.onload = (event)=>{
          let data = JSON.parse(event.target.result);
          $("#jsonArea").val(event.target.result);
          var finalXML = '<root>' + x2js.json2xml_str($.parseJSON(event.target.result)) + '</root>';
          var finalName = event.target.files[0].name; //setting it here
          $("#xmlArea").val(finalXML);

          finalXML = finalXML.split('FORM3CA').join('FORM3CB');
          finalXML = finalXML.split('F3CA').join('F3CB');
          finalXML = finalXML.split('<CreationInfo>')[0] + '<CreationInfo><SWVersionNo>1.0</SWVersionNo><SWCreatedBy>SW20000</SWCreatedBy><JSONCreatedBy>SW20000</JSONCreatedBy><JSONCreationDate>2021-11-21</JSONCreationDate><IntermediaryCity>311</IntermediaryCity></CreationInfo>' + finalXML.split('</CreationInfo>')[1]
          finalXML = finalXML.split('I_We1').join('I_We');
          
          console.log(finalName); //here
        }
        reader.readAsText(event.target.files[0]);
    }
 
document.getElementById('file').addEventListener('change', onChange);

I was suggested to use event.target.files[0].name in order to get the filename of the uploaded file (by @HeryKurniawan in comments of this post). But, when I try to console.log()the finalName variable (as you can see in above code), it shows me this error –

enter image description here

What is wrong in my code? I have also tried using event.target.file.name & event.target.file[0].name, but that doesn’t work either. Kindly guide… Thanks! 🙂

How can I set default checked in Ag-Grid React.js?

I use react ag-grid and I have checkboxSelection on row. I want to default checked some rows, not checked some rows. How can I do that ?

columnDefinationVoucherList: [
                { headerName: "", cellRenderer: countCellIndex, width: 50, minWidth: 40, maxWidth: 50, editable: false, },
                { headerName: "Belge Kodu", field: "ApplicationVoucher.Voucher.VoucherCode", width: 50, minWidth: 50, maxWidth: 80, suppressSizeToFit: true, sortable: true },
                { headerName: "Belge Adı", field: "ApplicationVoucher.Voucher.VoucherName", width: 120, minWidth: 50, suppressSizeToFit: true },
                { headerName: "Seç", field: "", width: 90, minWidth: 10, suppressSizeToFit: true, maxWidth: 50, checkboxSelection: true, },
            ],

                                          <AgGridReact
                                            columnDefs={this.state.columnDefinationVoucherList}
                                            headerHeight={30}
                                            rowHeight={20}
                                            rowData={this.state.documentList}
                                            onColumnResized={true}
                                            enableCellChangeFlash={true}
                                            enableCellTextSelection={true}
                                            enableCellExpressions={true}
                                            enableSorting={true}
                                            enableFilter={true}
                                            enableGroupEdit={true}
                                            enableRangeHandle={true}
                                            defaultColDef={this.state.shortGridDefaultColDef}
                                            rowSelection={'multiple'}
                                            onSelectionChanged={this.GetSelectedVouchers}
                                        >
                                        </AgGridReact>

Also I use enterprise mode. So I am open every solutions.

When Focus done on input field, fields remove the data

I am trying to input data using this function. this function is fetching data and doing formfilling but when the form focus on the input field or I try to submit from all, data disappears from all the fields and all input fields become red.

 if (Data[key].formname) {   
          $("[formcontrolname='"+Data[key].formname+"']").focus(); 
          $("[formcontrolname='"+Data[key].formname+"']").val(Data[key].value);
                        
                        await wait (1000)                        
                    }

specific item from an object in local storage is not removing

let cartItems = localStorage.getItem("ProductsinCart");
cartItems = JSON.parse(cartItems);
Object.values(cartItems).map(item => {

    let productNumbers2 = localStorage.getItem('cartNumbers2');
    productNumbers2 = parseInt(productNumbers2);
    let cartcost = localStorage.getItem('totalCost');
    cartcost = parseFloat(cartcost);
    let inCart = item.inCart;
    if (item.id === id)
    {

        localStorage.removeItem(cartItems[item.tag]);
        console.log(cartItems);
   
    }

CodingAllInOne:
description: “notNow”
id: 4
imgSrc: “./imagesForCart/programmingBooks/CodingAllInOne.jfif”
inCart: 1
inStock: 39
name: “Coding All In One”
price: 29.99
tag: “CodingAllInOne”
[[Prototype]]: Object
DesignPatterns:
description: “notNow”
id: 6
imgSrc: “./imagesForCart/programmingBooks/DesignPatterns.jfif”
inCart: 1
inStock: 39
name: “Design Patterns”
price: 9.99
tag: “DesignPatterns”
[[Prototype]]: Object