Auto input hidden value

I am trying to make a custom unsubscribe page (in pardot), I used the inspect tool and grabbed the current HTML code, I’m running into an issue with the input field, this is what the code currently looks like:

<input type="text" name="piEmailPrefEmail" id="piEmailPrefEmail"
 value="m******s@t*****x.com" class="text" readonly="readonly" >

The value needs to change so that it is not my email. Ideally I would like it to pull the users email the same way it does mine, with the hidden characters. Not sure what I need to update in the HTML and or what javascript code needs to be added.

I tried removing my email address and leaving the value field blank, which works when I remove “readonly” but ideally the user will not need to put in their own email address.

Using an async IIFE to run loops in the background in Javascript

Currently I am using an async IIFE like this:

(async () => {
  while(true) {
    ...game loop
  }
})()

The game loop is used to draw animations in a canvas element.
This works fine, (even though microtasks aren’t ran on a new thread), yet I have never seen it mentioned anywhere on the internet, so my question is, is this ok (will it run on all browsers, does it block something important), or should I use something like setTimeout?

How to filter out a key from a second level object of a nested array of objects

I am trying to filter out a key, in this case, count from a nested array of objects.

I have

let test  = [
 {
  "id": "c3c6f410f58e5836431b473ebcf134756232d04f2bf35edff8",
  "label": "Sector2",
  "options": {
   "62f92fab79ac81d933765bd0bbc4a1f5ea26cb3a088bcb4e6e": {
    "index": 0,
    "value": "Bob",
    "label": "Bob",
    "count": 1
   },
   "2fe91aa3567c0d04c521dcd2fc7e40d7622bb8c3f594d503da": {
    "index": 1,
    "value": "Student",
    "label": "Student",
    "count": 1
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc543e4": {
    "index": 2,
    "value": "BBB",
    "label": "BBB",
    "count": 1
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc54AAA": {
    "index": 3,
    "value": "Orange Duck",
    "label": "Orange Duck",
    "count": 1
   }
  }
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e951709485",
  "label": "Brown Cow"
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e95170ZZZ",
  "label": "Red Fish"
 }
]

 test = test.filter(item => item[0].options['count']);

but I am getting Cannot read properties of undefined

I am trying to filter out count from all elements of test that have options

desired output is

Thanks

[
 {
  "id": "c3c6f410f58e5836431b473ebcf134756232d04f2bf35edff8",
  "label": "Sector2",
  "options": {
   "62f92fab79ac81d933765bd0bbc4a1f5ea26cb3a088bcb4e6e": {
    "index": 0,
    "value": "Bob",
    "label": "Bob"
   },
   "2fe91aa3567c0d04c521dcd2fc7e40d7622bb8c3f594d503da": {
    "index": 1,
    "value": "Student",
    "label": "Student"
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc543e4": {
    "index": 2,
    "value": "BBB",
    "label": "BBB",
    "count": 1
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc54AAA": {
    "index": 3,
    "value": "Orange Duck",
    "label": "Orange Duck"
   }
  }
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e951709485",
  "label": "Brown Cow"
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e95170ZZZ",
  "label": "Red Fish"
 }
]

Javascript loaded but not working on Elementor backend

Good evening everybody
I’m writing an addon for Elementor to display a map and a graph, based on a kml file.
The addon works on the frontend, so I believe that the JS is pretty ok.

The JS code has some problem in the backend. I believe that something happens too late.

The render function of my addon is very simple:

protected function render() {
    $settings = $this->get_settings_for_display();
    $kmlUrl = $settings['kml_url'] ? $settings['kml_url'] : null;

    echo "<div id='kgm-map-container' data-kml='{$kmlUrl["url"]}' >";
        echo '<div id="kgm-map">loading map...</div>';
        echo '<div id="kgm-elevation_chart">loading chart...</div>';
    echo '</div>';
}

$kml_url is taken from a addon control, as you can see, then added as a meta attribute to my output.

The part of the JS that uses this information is this one:

jQuery(document).ready(function () {
  kmlFile = jQuery("#kgm-map-container").data("kml");

  console.log(document.getElementById("kgm-map-container"));
  
  var latlng = new google.maps.LatLng(0, 0);
  var mapOptions = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DEFAULT,
    },
  };
  mapInstance = new google.maps.Map(document.getElementById("kgm-map"), mapOptions);
  ... and so on

Pay attention now: the line “console.log(document.getElementById(“kgm-map-container”));” returns null, that’s why the map is not shown in the backend.

I see that jQuery(document).ready(..) is not the correct place to read my data, because they’re not available yet.

So, how can I patch this code? Is there a good Elementor hook that runs at the right time?
I tried with “elementor/frontend/init” but it’s clearly not working in the backend.
I tried with “elementor/frontend/init”, but it breaks both frontend and backend.

I need your help!
Thanks

How to discover the ideal dimensions (X, Z, Y) of a package that is capable of storing all products with the smallest possible empty space [closed]

Based on an array of products, each with varying X, Y and Z dimensions, discover the ideal size of a package that is capable of storing all products with as little empty space as possible.

https://i.sstatic.net/H3sR1qQO.jpg

I don’t want to base it on a package or box size, but rather figure out the ideal size based on the products.

I haven’t found anything that does this efficiently.

How to place elements in a grid

I have a grid layout made of 9 columns and 5 rows so 45 cells
enter image description here

Now I need to place a dynamic number of circles in this layout. The number of circles varies from a minimum of 1 to a maximum of 9. The position of these circles in the grid should follow the following rules:

enter image description here

So:

  • if the number of circle is 1, the circle center should be in the cell of column 5 and row 3
  • if the number of circles is 2, the first circle center should be in the cell of column 3 and row 3 and the second circle center should be in the cell of column 7 and row 3

The radius of the circle can varie too, but at the moment is not important since I was thinking to place circles in absolute.

How can I do that? Is there a library or something like that that can help me?
I’m using React.

Here a codesandbox

Uncaught ReferenceError: process is not defined in the frontend code using React and Firebase

I am developing a frontend application using React and Vite. I have cloned a React/Bootstrap theme template and am modifying it for my project. However, I have encountered an error when attempting to configure and initialize Firebase for authentication.

Here is the code I am trying to implement:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

console.log(process.env);

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);  // gives us an auth instance

export default auth;   // in order to use this auth instance elsewhere

However, when I try to run the project and open the console window in Google Chrome, I receive the following error:

Uncaught ReferenceError: process is not defined
    at firebase.js?t=1714400003156:4:13

I am unsure as to why this error is occurring, especially as I have ensured that the process.env instances in my code correctly correspond to variables in my .env file.

How to download each task data into a column of its own using javascript

I am creating a chrome extension but I am stuck at the point where I need to download the tasks data into a csv file. The download is happening fine, I am having a small issue with the formatting. Currently, the task details are stacked on top of each other but my desire is to have each task in its own column for easier management.

My code:

const exportTasksBtn = document.getElementById('export-tasks-btn');
exportTasksBtn.addEventListener('click', exportTasks);

function exportTasks() {
    chrome.storage.local.get('tasks', function (data) {
        const tasks = data.tasks || [];
        if (tasks.length === 0) {
            console.log('No tasks to export');
            return;
        }

        // Create CSV content
        let csvContent = 'data:text/csv;charset=utf-8,';
        
        // Add task data
        tasks.forEach(task => {
            // Concatenate headers and values in the same cell
            csvContent += `ID: ${task.id}n` +
                          `File Types: ${task.fileTypes.join(', ')}n` +
                          `Prefix: ${task.prefix || ''}n` +
                          `Suffix: ${task.suffix || ''}n` +
                          `Folder Name: ${task.folderName || ''}n` +
                          `Download Time: ${task.downloadTime || ''}n` +
                          `Zip Download: ${task.zipDownload ? 'Yes' : 'No'}n` +
                          `Status: ${task.status || ''}n`;

            // Add URL heading
            csvContent += `URLn`;

            // Add URLs
            task.urls.forEach(url => {
                csvContent += `${url}n`;
            });

            // Add an empty line to separate tasks
            csvContent += 'n';
        });

        // Create a download link
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "tasks.csv");
        document.body.appendChild(link);

        // Trigger the download
        link.click();
    });
}

Current Output

enter image description here

Intended output:

enter image description here

Material UI cutom colors

Goodmorning everybody,

I am trying to develop a website using ReactJS and Material UI.
I started from this template.

I would like to modify the color of the TextField when focused: now it is blue, let’s say that I want it to be green.

This was the original file (in the repo that i linked above, it is under src/components/MKInput/MKInputRoot):

import TextField from "@mui/material/TextField";
import { styled } from "@mui/material/styles";

export default styled(TextField)(({ theme, ownerState }) => {
  const { palette, functions } = theme;
  const { error, success, disabled } = ownerState;

  const { grey, transparent, error: colorError, success: colorSuccess } = palette;
  const { pxToRem } = functions;

  // styles for the input with error={true}
  const errorStyles = () => ({
    backgroundImage:
      "url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23F44335' viewBox='0 0 12 12'%3E%3Ccircle cx='6' cy='6' r='4.5'/%3E%3Cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3E%3Ccircle cx='6' cy='8.2' r='.6' fill='%23F44335' stroke='none'/%3E%3C/svg%3E")",
    backgroundRepeat: "no-repeat",
    backgroundPosition: `right ${pxToRem(12)} center`,
    backgroundSize: `${pxToRem(16)} ${pxToRem(16)}`,

    "& .Mui-focused": {
      "& .MuiOutlinedInput-notchedOutline, &:after": {
        borderColor: colorError.main,
      },
    },

    "& .MuiInputLabel-root.Mui-focused": {
      color: colorError.main,
    },
  });

  // styles for the input with success={true}
  const successStyles = () => ({
    backgroundImage:
      "url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 8'%3E%3Cpath fill='%234CAF50' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3E%3C/svg%3E")",
    backgroundRepeat: "no-repeat",
    backgroundPosition: `right ${pxToRem(12)} center`,
    backgroundSize: `${pxToRem(16)} ${pxToRem(16)}`,

    "& .Mui-focused": {
      "& .MuiOutlinedInput-notchedOutline, &:after": {
        borderColor: colorSuccess.main,
      },
    },

    "& .MuiInputLabel-root.Mui-focused": {
      color: colorSuccess.main,
    },
  });

  return {
    backgroundColor: disabled ? `${grey[200]} !important` : transparent.main,
    pointerEvents: disabled ? "none" : "auto",
    ...(error && errorStyles()),
    ...(success && successStyles()),
  };
});

I simplified it a little:

import TextField from "@mui/material/TextField";
import { styled } from "@mui/material/styles";

export default styled(TextField)(({ theme, ownerState }) => {
  const { palette } = theme;
  const { disabled } = ownerState;

  const { grey, transparent } = palette;

  const myStyles = () => ({
    "& .Mui-focused": {
      "& .MuiOutlinedInput-notchedOutline, &:after": {
        borderColor: "#00ff00",
      },
    },

    "& .MuiInputLabel-root.Mui-focused": {
      color: "#00ff00",
    },
  });

  return {
    backgroundColor: disabled ? `${grey[200]} !important` : transparent.main,
    pointerEvents: disabled ? "none" : "auto",
    ...myStyles(),
  };
});

I removed the error && before ...myStyle() as I want this style to always be appliend, not only on error.

Now suppose I want to change from green to red, I replace the strings “#00ff00” with “#ff0000”, click on the text input on my webpage and the border becomes red when focused. If I refresh the page and do that again, the border is blue on focus. This happens every time I try to change color: I replace the color string with the desired one, and the correct color is applied until I refresh the page; after refresh, focus border color always goes back to blue.

Any suggestion on why this may happen?

Let me know if you need further details.

Thanks in advance

I cannot upload multiple files in my html template

I am making a site where you can send your game with multiple additional images. I upload images and they are send to API. Then when you open the game page there is a request to API and it returns the image. The problem is that when I try to upload multiple images only last one uploads. This is my html form

{% extends "base.html" %}
{% block body %}
<form id="chloroform" action="/senddata" method="post" enctype=multipart/form-data >
  <h2>Загрузить игру</h2>
  <fieldset>
    <legend>Основные данные</legend>
      <label for="title">Название игры:</label>
      <input type="text" name="title"  id="title" maxlength="24" required>
  </fieldset>

      <div class="container col-md-6" style="float:right; position: relative; top: -100px; left: 20px">
    <p style="outline:2px solid #555; border-radius:5px; width: 300px; height: 300px;">
        <img id="frame" src="" class="img-fluid" style="max-width: 300px; max-height: 300px;  " />
    </p>

    <div class="mb-5">
        <input class="form-control" name="prev" type="file" id="formFile" onchange="preview()" accept="image/png" required>
    </div>
</div>

<script>
    function checkImage(file) {
        return new Promise((resolve, reject) => {
            if (file.type === 'image/png') {
                const img = new Image();
                img.onload = () => {
                    if (img.width === img.height) {
                        resolve();
                    } else {
                        reject(new Error('Изображение должно быть квадратным!'));
                    }
                };
                img.src = URL.createObjectURL(file);
            } else {
                reject(new Error('Изображение должно быть в формате PNG!'));
            }
        });
    }

    function preview() {
        const file = event.target.files[0];
        checkImage(file)
            .then(() => {
                const frame = document.getElementById('frame');
                frame.src = URL.createObjectURL(file);
                frame.style.display = 'block';
            })
            .catch(error => {
                alert(error.message);
                document.getElementById('formFile').value = null;
                const frame = document.getElementById('frame');
                frame.src = '';
                frame.style.display = 'none';
            });
    }
</script>

<!-- THIS IS IMAGES WHERE I GET THE PROBLEM-->
  <fieldset>
      <legend>Additional data</legend>
      <div>
          <textarea name="desc" placeholder="Brief description" id="desc" style="width: 312px; height: 150px;" required></textarea>
      </div>
      <div>

      </div>
  </fieldset>
    <fieldset>
        <div>
            <legend for="file" class="form-label">Zip file </legend>
            <input class="form-control form-control-lg" name="file" id="file" type="file" accept=".zip" required>
            <script>
document.getElementById('file').onchange = function(e) {
    if(!e.target.files[0].name.match(/.(zip)$/)) {
        alert('Only .zip!');
        e.target.value = '';
    }
};
</script>
        </div>
<div>
    <legend for='files'>Select additional images: </legend>
    <label>Only png!</label>
    <input id='files' type='file' class="btn btn-outline-info" name="files" accept="image/png" multiple>
</div>
    </fieldset>
    <div>
        <button  type="submit">Submit</button>
    </div>
</form>
{% endblock %}

And here i try to retrieve the data

@app.route('/senddata', methods=['POST', 'GET'])
def senddata():
    url = f"{api_url}/games"
    if request.method == 'POST':
        title = request.form.get('title')
        desc = request.form.get('desc', '')
        author = int(current_user.get_id())
        prev_file = request.files['prev']
        zip_file = request.files['file']
        files = request.files.getlist('files')
        if not prev_file.filename.endswith('.png'):
            prev_file = open('url_for(static, filename=images/default.png)', 'rb')
        images = []
        for file in files:
            if file.filename.lower().endswith('.png'):
                images.append(("png", file.read()))
                print('Check')
        data = {
            "title": title,
            "desc": desc,
            "author": author,
            "prev": ("png", prev_file.read()),
            "file": ("zip", zip_file.read()),
            "images": images
        }
        requests.post(url, data=pickle.dumps(data)).json()
        return redirect('/index')

And here I try to use the data

<div id="info" style="width: 48vw">
    <p id="infoframe" style="outline:2px solid #555; border-radius:5px; width: 100%; min-height: 15vw;">
        {{game['desc']}}
    </p>
    <div id="imgframe" style="width: 100%">
        <div id="images" class="carousel slide carousel-fade" data-bs-ride="carousel" style="width: max-content; margin: auto">
            <div class="carousel-inner">
                {% for image in game['images'] %}
                <div class="carousel-item {% if loop.first %}active{% endif %}">
                    <img src="{{api_url}}/file?p={{image['img']}}" class="d-block w-100" style="max-width: 20vw;max-height: 20vw;">
                </div>
                {% endfor %}
            </div>
            <button class="carousel-control-prev" type="button" data-bs-target="#images" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Предыдущая</span>
            </button>
            <button class="carousel-control-next" type="button" data-bs-target="#images" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Следующая</span>
            </button>
        </div>
    </div>
</div>

I am kind of a newbie to python and html so I kind of do not understand how this works and why it doesn’t work as inteded.

I have seen that I need multiple so I used it in

<input id='files' type='file' class="btn btn-outline-info" name="files" accept="image/png" multiple>

but it still sent only the last image

How can I set cursor position in a text field?

I’m actually working on a PDF in Acrobat Pro 2017.
I have 2 multilines text fields (tfDeclaration1 and tfDeclaration2) and and when the first one is full, the text flows to the second text field. That works just fine with this script being attached on the first text field on keystroke event :

var t = this.getField("tfDeclaration2");

if (event.fieldFull) {
    t.setFocus();

    if (t.value != "") {
        // set cursor at the beginning of tfDeclaration2
    }
}

What I want next is if the 2nd textfield has already some text, I want the cursor to be set to the first character (position 0) instead of at the end. (that’s what setfocus does)

Is there a way to achieve that ?

I’ve tried a few things setSelectionRange(), moveStart(), setStart() but none of these worked.

Thank you and have a great day.

Saving File on User`s device on custom location

I am asking this as part of latest developments up until 2024 taken into consideration.

Only way I know is window.showSaveFilePicker which is supported on Chrome, Edge, Opera latest versions (https://caniuse.com/?search=showSaveFilePicker). But this approach didn’t work for me on the html app I am working on. If I go to Google and enter this onto console, it loads up save dialog but if I load up this app and do window.showSaveFilePicker method, it doesn’t work.

Is there any other way to allow user to save a file onto custom location on their computer each time they click save button? Apparently in python there is filedialog.asksaveasfile that we can use, how would we use this in conjunction with HTML frontend?

Laravel Inertia React TypeError: this.resolveComponent is not a function

I have a laravel ap and I am trying to fetch some data from an external api and display this data with React.

There is a search field with a submit button and under this form a list of the results. When I press the search button the data gets fetched successfully from the external api but in my front end I can’t display the results my component stays empty. I think I’ve setup the routes wrong maybe? I think the issue is it tries to redirect to ‘/’ and that empties the results everytime ? Something is not correct there I think.

In my console I get this error after submitting:

Uncaught (in promise) TypeError: this.resolveComponent is not a function

My Kernel.php

class Kernel extends HttpKernel
{
    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareHandleInertiaRequests::class,
        ],
    ];
}

Routes in web.php

Route::controller(LegoController::class)->group(function ()  {
    Route::get('/','index')->name('lego.index');
    Route::get('/searchParts','searchParts')->name('lego.searchParts');
});

LegoController.php

class LegoController extends Controller
{
    public function __construct(private LegoProvider $legoProvider)
    {
    }

    public function index()
    {
        return Inertia::render('Index');
    }

    public function searchParts(Request $request): Response
    {
        if (!$request->setNumber) {
            return Inertia::render('PartsList', ['parts' => Collection::make()]);
        }

        return Inertia::render('PartsList', ['parts' => $this->legoProvider->getPartsBySet($request->setNumber)]);
    }
}

Index.jsx

import React, { useState } from 'react';
import { router } from '@inertiajs/react'
import PartsList from "./PartsList.jsx";

const Index = () => {
    const [values, setValues] = useState({
        setNumber: "",
    });

    function handleChange(e) {
        const key = e.target.id;
        const value = e.target.value
        setValues(values => ({
            ...values,
            [key]: value,
        }))
    }

    function handleSubmit(e) {
        e.preventDefault()
        router.get('/searchParts', values)
    }

    return (
        <>
            <h1>Search parts by set number</h1>
            <hr/>
            <form onSubmit={handleSubmit}>
                <label htmlFor="setNumber">Set Number:</label>
                <input id="setNumber" value={values.setNumber} onChange={handleChange} />
                <button type="submit">Search</button>
            </form>

            <PartsList />
        </>
    )
}

export default Index

PartsList.jsx

import React, { useState } from 'react';

const PartsList = ({ parts }) => {
    return (
        <>
            <h1>Parts</h1>
            <hr/>
            { parts && parts.map( (part) => (
                <div key={part.id}>
                    <h2>{part.partName}</h2>
                    <a href={part.partUrl}>{part.partNumber}</a>
                </div>
            )) }
        </>
    )
}

export default PartsList

Inject JS code into cefsharp(inject youtube iframe)

I looked into lots of writing so I thought the code that I wrote should be working as well but it doesn’t. So I need help with finding out what is wrong with my code.

    private void Music_Control_JS(object sender, FrameLoadEndEventArgs e)
    {
        if (e.Frame.IsMain)
        {
            string url = e.Frame.Url;

            if (url.Contains("?autoplay=1"))
            {
                music_player.ExecuteScriptAsync(@"
                var tag = document.createElement('script');
                tag.src = 'https://www.youtube.com/iframe_api';
            ");
                music_player.ShowDevTools();
            }
        }
    }

so what I’m trying to do here is whenever music is played(“autoplay=1”) cefsharp will be loaded with youtube video and automatically play but in the meanwhile, I want to inject js code in to html. But it seems like it is not working. I check js is not injected using showdevtools.

what I’m trying to do using iframe api is to control youtube video using c# component(button, slider, etc)

RSA Implementation in React-JS

I have a backend in java-spring boot. I implemented RSA in Java in API call, such that every API request should be done with encrypted data and response should be decrypted . The java code is as:

public static String encrypt(String strToEncrypt){
   try {
        byte[] keyBytes = Files.readAllBytes(Paths.get(PUBLIC_KEY_FILE));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] strBytes = strToEncrypt.getBytes("UTF-8");
        int inputLength = strBytes.length;
        int offset = 0;
        int maxBlockSize = 245;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        while (inputLength - offset > 0) {
            byte[] block;
            if (inputLength - offset > maxBlockSize) {
                block = cipher.doFinal(strBytes, offset, maxBlockSize);
            } else {
                block = cipher.doFinal(strBytes, offset, inputLength - offset);
            }
            outputStream.write(block, 0, block.length);
            offset += maxBlockSize;
        }

        byte[] encryptedBytes = outputStream.toByteArray();
        return Base64.getEncoder().encodeToString(encryptedBytes) + SUFFIX;
    } catch (Exception e) {
        System.out.println("Error encrypting string: " + e.getMessage());
        return strToEncrypt;
    }
}

public static String decrypt(String strToDecrypt) {
    try {
        if (strToDecrypt == null || strToDecrypt.isEmpty() || !strToDecrypt.endsWith(SUFFIX)) {
            return strToDecrypt;
        }
        strToDecrypt = strToDecrypt.replace(SUFFIX, "");

        byte[] keyBytes = Files.readAllBytes(Paths.get(PRIVATE_KEY_FILE));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] encryptedBytes = Base64.getDecoder().decode(strToDecrypt);
        int inputLength = encryptedBytes.length;
        int offset = 0;
        int maxBlockSize = 256;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        while (inputLength - offset > 0) {
            byte[] block;
            if (inputLength - offset > maxBlockSize) {
                block = cipher.doFinal(encryptedBytes, offset, maxBlockSize);
            } else {
                block = cipher.doFinal(encryptedBytes, offset, inputLength - offset);
            }
            outputStream.write(block, 0, block.length);
            offset += maxBlockSize;
        }

        byte[] decryptedBytes = outputStream.toByteArray();
        return new String(decryptedBytes, "UTF-8");
    } catch (Exception e) {
        System.out.println("Error decrypting string: " + e.getMessage());
        return strToDecrypt;
    }
}

`

How do I implement this in react? I have a two set of Key-Pair , How should i do it ? Is there any way to do with single pair of keys ? . Please explain and provide the react-js code.