How to call a parent component method (or lift of state) from a custom React-Select MenuList component?

I have created a custom MenuList button (“Add New User”) at the bottom of a React-Select element to allow for adding another user to the select list. However, I am having trouble figuring out how to handle the event once a new user is created. The codesandbox below contains a simplified version. Specifically, line 29 this._loadData(randomId) does not have the scope to access this of the parent component (obviously). My question is, how to I add a “handleEvent” property so that I can lift up state to the parent component for this custom MenuList component?

Edit react-select-custom-event-handler

Code snippet for the custom MenuList component allowing the user to add a new AppUser:

const MenuButtonAddNewUser = (props) => {
  return (
    <components.MenuList {...props}>
      {props.children}
      <div className="border-top text-center py-2">
        <a
          href="showModalUrl.action"
          onClick={(event) => {
            event.preventDefault();

            // Simluate opening a modal and adding a user
            let randomId = Math.floor(Math.random() * (10 - 4 + 1)) + 4;
            console.log(
              "Simluate loading modal and adding a user with id: " + randomId
            );

            // Tell parent componenent to reload the options from the database
            // and auto-select the new user
            // How do I gain access to "_loadData"???
            //this._loadData(randomId);
            console.log(
              "User added. Call 'this.loadData(" + randomId + ")' here!!"
            );
          }}
        >
          <i className="fa fa-fw fa-user-plus mr-1" /> Add New Agent
        </a>
      </div>
    </components.MenuList>
  );
};

Apply CSS conditionally in a loop – VueJS

I have a JSON list of items that I import in my vue component,
I loop though that file in order to show them. Each item belong to a specific ‘group’ :

See IMG

E.g. :

{
"type": "Simple list",
"title": "Simple list",
"id": 1,
"group": "list-component",
"properties": "lorem lipsum"
},

I would like to apply a CSS ‘border-top-color’ to each item according to its group.

I was trying to make a JS method but I’m not sure how to achieve that. Here’s my atempt.

The template (I’m using VueDraggable, don’t mind it) :

          <div class="item drag" :key="element" :style="[{ 'border-top-color': 'brdrTpClr' }]">
            {{ element.title }}
            <div class="addico" :key="index">
              <i class="fas fa-add"@click="$emit('pushNewElt', element.id)"></i>
            </div>
          </div>

The script :

data() {
    return {
      dragItems: dragItemsList,
      brdrTpClr: "",
    };
  },
  mounted() {
    for (let i = 0; i <= 15; i++) {
      if (this.dragItems[i].group == "list-component") {
         // I'm not sure how to do it
        // the color I want to apply : #00A3A1b
      } else if (this.dragItems[i].group == "location-media-component") {
        // #005EB8
      } else if (this.dragItems[i].group == "container-component") {
        // #0091DA
      } else if (this.dragItems[i].group == "UI-component") {
        // #6D2077
      } else if (this.dragItems[i].group == "reader-scanner-component") {
        // #470A68
      }
    }
  },

I’m using i<=15 instead of i<=this.dragItems.length because of a bug, don’t mind it too.

value in jquery.min.js selectors

I’m using jquery and I have a question.

=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)
return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}
else while(b=a[d++])c+=e(b);return c},
d=*ga.selectors={cacheLength:50,*createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}}

What does the selectors = {cacheLength: mean in jquery.min.js?
and also is it possible to change the value of cacheLength?

ReactJS – Passing a component as a return

Im using React, useState and React-Icons.

My intention is to create a dropdown menu (without Bootstrap). I want to change the icon when clicked (to init the function) but the output is the raw SVG details. Any ideas?

import { IoMdArrowDropdownCircle, IoMdArrowDropupCircle } from "react-icons/io";

function navBar() {
  const navToggle = () => {
    const [navMenuToggle, changeNavToggle] = useState(true);
    return navMenuToggle ? (
      <IoMdArrowDropdownCircle />
    ) : (
      <IoMdArrowDropupCircle />
    );
    changeNavToggle(false);
  };
<div className="tableIcon" id="navDropdown" onClick={navToggle}>
  <IoMdArrowDropdownCircle />
</div>

What am I missing? Calculation won’t show in the field

I am trying to make an area calculator and I cannot figure out what am I missing.

the area field is not updating when entering numbers in each field.

Any advice please? I wonder if I’m missing something very important.

Many thanks in advance

Here is my html:

                <tr>
                    <th style="text-align: left;"><label>Slab Width (m): </label></th>
                    <th><div class="input-box">
                        <input type="text" name="slab_width" onkeypress="return isNumber(event)" onkeyup="calculateArea()" required="" class="form-control">
                    </div></th>
                </tr>
                <tr>
                    <th style="text-align: left;"><label>Slab Length (m): </label></th>
                    <th><div class="input-box">
                        <input type="text" name="slab_length" onkeypress="return isNumber(event)" onkeyup="calculateArea()" required="" class="form-control">
                    </div></th>
                </tr>
                <tr>
                    <th style="text-align: left;"><label>Total Area (m2):</label></th>
                    <th><div class="input-box">
                       <input type="text" name="slabsArea" disabled="" class="form-control">
                    </div></th>
                </tr>
            
            </table>```


             And here is the script for it:

    function calculateArea() {
    var form = document.getElementById("calc");
    var sLength = parseFloat(form.elements["slab_length"].value);
    var sHeight = parseFloat(form.elements["slab_width"].value);

    var slabsArea = slabWidth * slabLength;
    
    //slabsArea = Math.round(slabsArea);
    //document.getElementById("slabsArea").value = slabsArea;
    form.elements["slabsArea"].value = slabsArea;
return slabsArea;

        }



location props in gatsby is not defined

I am trying to use location props in my gastby page :
I am passing props in my Link in
pages/index.js:

 <Link state={{eventID: event.id}}  to={`/date/${event.name}`}>
  </Link>

pages/date/[dateId]/index.js:

const DateWithId = ({location},props) => {
    const { state = {} } = location
    const { eventID} = state
...}

eventually I get an error Parsing error: Identifier ‘location’ has already been declareded :
enter image description here

Using PDF-Lib to create a document and print without saving the document locally

Within my web application, I am attempting to create a PDF document (which I am doing successfully) and then print it.

Most of the solutions I have found said that you will have to do it server-side probably with some PHP, which would be fine. but If I did that, I would have no clue how to do this.

The application is only really used by one machine and it is not distributed on the web so it is locally hosted only so no need for another end-user computer.


Application Goal / Expected result

I would like the application to:

  • Generate a PDF based on the user’s input (DONE AND WORKS)
  • Use the PDF and PRINT straight away

So it appears I would have a few viable options…

  • PDF-Lib client-side only (possible client-side DB?)
  • PDF-Lib client-side and a server-side link using PHP?
  • Fully server-side
  • A base 64 link?

I have tried locally saving it to the machine and using the file but it will not allow me, unfortunately 🙁

HTML

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Your Certificate for The Event</title>
    <link rel="stylesheet" href="style.css">
    <link rel="favicon" href="favicon.ico">
</head>

<body>
    <header>
        <img src="FR_Logo.png" alt="FRSystems Logo" width="500" height="250" />
        <h4>Get your certificate of your laps</h4>

    </header>
    <main>

        <label for="name">Type Your Name</label>
        <input required type="text" name="Name" autocomplete="name" placeholder="" id="name" minlength="1"
               maxlength="16">
        <Button id="submitBtn">Get Certificate</Button>


    </main>

    <script src="https://unpkg.com/pdf-lib/dist/pdf-lib.js"></script>
    <script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
    <iframe id="iframe"></iframe>

    <script src="./FileSaver.js"></script>
    <script src="https://unpkg.com/@pdf-lib/[email protected]"></script>
    <script src="./index.js"></script>
</body>

</html>

Index.JS

const userName = document.getElementById("name");
const submitBtn = document.getElementById("submitBtn");

const { PDFDocument, rgb, degrees, StandardFonts } = PDFLib;


const capitalize = (str, lower = false) =>
  (lower ? str.toLowerCase() : str).replace(/(?:^|s|["'([{])+S/g, (match) =>
    match.toUpperCase()
  );

submitBtn.addEventListener("click", () => {
  const val = capitalize(userName.value);

  //check if the text is empty or not
  if (val.trim() !== "" && userName.checkValidity()) {
    console.log(val);
    createPdf(val);
  } else {
    userName.reportValidity();
  }
});

function print() {
    var frame = document.getElementById('frame');
    frame.contentWindow.focus();
    frame.contentWindow.print();
};


function readURL(input) {
    console.log("GOT HERE");
//    if (input.files && input.files[0]) {
    console.log("GOT HERE 2");
    var reader = new FileReader();

    reader.onload = function (e) {
        console.log(e.target.result);
//            $('#pdfResult')
//                .attr('src', e.target.result);
    };
    reader.readAsDataURL(input.files[0]);
    console.log(reader.readAsDataURL(input.files[0]));

//    }
};

async function createPdf(val) {
    const pdfDoc = await PDFDocument.create();
    const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);

    const page = pdfDoc.addPage();
    const { width, height } = page.getSize();
    page.setSize(841.89, 595.28)
    // midpoint x = 420.945, y= 297.64

    console.log(page.getSize(),width,height)
    const fontSize = 30
    var textWidth = timesRomanFont.widthOfTextAtSize(val, fontSize);
    console.log(timesRomanFont.widthOfTextAtSize(val, fontSize))
    var textHeight = timesRomanFont.heightAtSize(fontSize);
    var nameY = ((page.getHeight() / 2) + 50) - (textHeight / 2);
    var centerY = page.getHeight() / 2 - textHeight / 2;
    var centerX = page.getWidth() / 2 - textWidth / 2;

    page.drawText(val, {
        x: centerX,
        y: nameY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });

    var score = "32"; // Would be taken from the database (Select query) using ID/ChipNumber
    var scoreString = "who completed " + score + " laps";
    var bottomText = "< EVENT NAME > on < LONG DATE >";
    var supportingText = "< Support Text >"

    var textWidthScoreString = timesRomanFont.widthOfTextAtSize(scoreString, fontSize);
    console.log(timesRomanFont.widthOfTextAtSize(scoreString, fontSize));
    var scoreY = ((page.getHeight() / 2) + 0) - (textHeight / 2);
    var scoreX = page.getWidth() / 2 - textWidthScoreString / 2;

    var bottomTextWidthString = timesRomanFont.widthOfTextAtSize(bottomText, fontSize);
    var bottomTextY = ((page.getHeight() / 2) - 50) - (textHeight / 2);
    var bottomTextX = page.getWidth() / 2 - bottomTextWidthString / 2;


    var supportingTextWidthString = timesRomanFont.widthOfTextAtSize(supportingText, fontSize);
    var supportingTextY = ((page.getHeight() / 2) - 100) - (textHeight / 2);
    var supportingTextX = page.getWidth() / 2 - supportingTextWidthString / 2;


    page.drawText(scoreString, {
        x: scoreX,
        y: scoreY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });

    page.drawText(bottomText, {
        x: bottomTextX,
        y: bottomTextY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });

    page.drawText(supportingText, {
        x: supportingTextX,
        y: supportingTextY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });


    const pdfBytes = await pdfDoc.save();

    console.log(pdfBytes);
    console.log(pdfDoc)

    // Create a new file
    // This uses File Saver to save the files, i used this to temp save whilst i moved around the text
    var file = new File(
        [pdfBytes],
        "test-Certificate.pdf",
        {
            type: "application/pdf;charset=utf-8",
        }
    );
    console.log(file);





//    var iframe = document.getElementById('iframe');
//    iframe.src = file;
//    iframe.contentWindow.focus();
//    iframe.contentWindow.print();
//    readURL(file);
//    saveAs(file);
    console.log(saveAs(file));

};

From .map get product ID and search from another json text with same id and replace it to name

I need advice.
via .map I get the product id (item.id), and from another JSON text I would need it to find in it the number of that id and take the same id found product_name and rewrite the product id to that product_name from the second JSON text.

https://justpaste.it/4cik4

{ subCategoryList && (
                
                    subCategoryList.map(function(item, id) {
                        return(
                          <tr key={id}>
                            <td>{item.subproduct_name}</td>
                            <td>{item.products_id}</td> <--- HERE
                            <td>{item.product_url_header}</td>
                            <td className='action'> <i class='bx bx-pencil hover' onClick={()=>editSubcategoryRecord(item.id, item.products_id, item.subproduct_name, item.product_url_header)}></i> <i class='bx bx-trash-alt hover' onClick={()=>deleteSubCategory(item.id)}></i> </td>
                          </tr>
                    )}.bind(this))

                  )
                }

Download string data as file based on the file type (text/Json)

I am trying to downloading a string data as file such as text, and json files based on the fileType we are passing as parameter. I have tried below code.

function downloadString(text, fileType, fileName) {
  var blob = new Blob([text], { type: fileType });

  var a = document.createElement('a');
  a.download = fileName;
  a.href = URL.createObjectURL(blob);
  a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
  a.style.display = "none";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500);
}

Downloading is working. But it always download txt file even if we pass json filetype.
Can anyone help this?

Cannot read properties of null (reading ‘style’) at X [duplicate]

Similar to what I did in other parts of the document and worked, I was trying to hide the delete button if an user isn’t logged in or in other profile. However, I get this message “Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘style’)
at showEditDelete”, pointing to the delete deleteBtn.display.style

async function showEditDelete() {
let deleteBtn = document.getElementById("delete-col");
let currentProfileId = await usersAPI_auto.getById(userId);
let loggedUserId = sessionManager.getLoggedUser().userId;
if (sessionManager.isLogged()){
    if (loggedUserId != currentProfileId){
        deleteBtn.style.display = "none"
    }
} else {
    deleteBtn.style.display = "none";  
}

}

Set CSS definition on an Angular Directive that applies to its children

Im trying to implement a responsive table directive in my angular app, which sets the min and max width and font-size of the columns in a MatTable.

These values are based on the parent containers width, and the number of columns.

The directive gets the column definitions as an input array of strings.(eg.[“ordernum”,”ordername”,”timestamp”])

Currently the code looks like this:


@Input('ResponsiveTable') columns: string[] = [];
...
constructor(
    private el: ElementRef,
    private host: MatTable<any>,
    private breakpointObserver: BreakpointObserver
  ) {}
....

 ngOnInit(): void {
    //set table style props
    this.el.nativeElement.style.minWidth =
      minCellWidth * this.columns.length + 'px';
    this.el.nativeElement.style.width = tableWidth + '%';

    // //subscriptions
    this.subscriptions.push(
      this.host.contentChanged.subscribe(() =>
        setTimeout(() => this.initStyle())
      )
    );
  }

  
...
  initStyle() {
    //get tableSize
    const parentWidth = this.el.nativeElement.parentNode.clientWidth;
    this.maxColumnWidth =
      parentWidth / this.columns.length > minCellWidth
        ? parentWidth / this.columns.length
        : minCellWidth;

    //set the headers, and maxWidth
    this.el.nativeElement.querySelectorAll('th').forEach((header: any) => {
      header.style.maxWidth = this.maxColumnWidth + 'px';
      header.style.fontSize = `calc(8px + 0.25vw + 0.5vw / ${this.columns.length})`;
      header.style.padding = '6px';
    });

    //set the table cells and maxWidth
    this.el.nativeElement.querySelectorAll('td').forEach((cell: any) => {
      cell.style.maxWidth = this.maxColumnWidth + 'px';
      cell.style.fontSize = `calc(8px + 0.25vw + 0.5vw / ${this.columns.length})`;
    });

    this.initBreakpointObserver();

    this.tableWidth = this.el.nativeElement.width;
  }

I think this is not efficient, because every time a content change happens, I have to query all the cells and headers, to set their max and min width.

It would be nice to add some CSS to the parent element, that selects all its children mat-cells and mat-headers, and set their size. Sadly I cant use a classic CSS class beacause the size value is based on the number of table columns.

Is there a way to progmatically add a CSS class that selects all the children cells and applies the style to them, even if a new row is added?

Or what could be a better solution?

New array with non-repeating values [duplicate]

I need to create a findUnique() function that creates a new array with non-repeating values.

This is how it should be:

console.log([10, 5, 6, 10, 6, 7, 2].findUnique()) // [5, 7, 2]

My try:

Array.prototype.findUnique = function() {
    let arr = this;
    let newarr = arr.filter((v, i, a) => {
       return a.indexOf(v) === i
    })
    return newarr
}

But it returns:

[10, 5, 6, 7, 2]

How can I make it return only non-repeated values?