Using an image path passed in props React, without import

I have lots of images in my project that I want to use dynamically depending on the user’s needs. So I’m having a local db.js file having all the images paths and I’m passing them as props to be displayed but it’s not working. I also can’t import 50+ images in the component, there has to be an easier way.

function Component(props){
    return(
        <div>
            <img src={props.src} alt="..."/>
        </div>
    )
}

The above code doesn’t work as the relative path of the image is passed from the props, what can I do to dynamically import the passed path from the prop and use it in the src?

I tried this code to import the passed prop, but it didn’t work as well.

function Component(props){

    async function importImage(){
        const img = await import(props.src)
        return img.default
    }

    return(
        <div>
            <img src={importImage()} alt="..."/>
        </div>
    )
}

TypeError: chrome.setDefaultService is not a function

Microsoft Windows [versão 10.0.19045.2965]
(c) Microsoft Corporation. Todos os direitos reservados.

C:UsersDalianDownloadsExtras Tempapi-aviator-betano>npm install

up to date, audited 148 packages in 3s

17 packages are looking for funding
run npm fund for details

found 0 vulnerabilities

C:UsersDalianDownloadsExtras Tempapi-aviator-betano>npm start

[email protected] start
node src/server.js

C:UsersDalianDownloadsExtras Tempapi-aviator-betanosrcservicepainel-service.js:12
chrome.setDefaultService(new chrome.ServiceBuilder(chromeDriver.path).build());
^

TypeError: chrome.setDefaultService is not a function
at Object. (C:UsersDalianDownloadsExtras Tempapi-aviator-betanosrcservicepainel-service.js:12:8)
at Module._compile (node:internal/modules/cjs/loader:1267:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1321:10)
at Module.load (node:internal/modules/cjs/loader:1125:32)
at Module._load (node:internal/modules/cjs/loader:965:12)
at Module.require (node:internal/modules/cjs/loader:1149:19)
at require (node:internal/modules/helpers:121:18)
at Object. (C:UsersDalianDownloadsExtras Tempapi-aviator-betanosrcserver.js:3:48)
at Module._compile (node:internal/modules/cjs/loader:1267:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1321:10)

Node.js v20.1.0

C:UsersDalianDownloadsExtras Tempapi-aviator-betano>

I tried to run this https://github.com/epedrotti7/api-aviator-betano following the instructions contained therein. But it gives an error when I run npm start

How to display input options only after selecting an option from the ‘select class’ tag JQuery/JS?

Im trying to create this form page https://docs.google.com/document/d/1wu2J2Jp4KAYEVyQ6B7KSGFp_7oeDttH7DwOPLMARfws/edit . I already have a form ready for data insertion to database. I just need to stylize it so that the form changes dynamically after selection change.

<fieldset>
            <label for="#productType">Type Switcher</label>
            <select id="#productType">
                <option>--Select a Type</option>
                <option value="DVD" id="#DVD" onchange="show(this)">DVD</option>
                <option value="Book" id="#Book" onchange="show(this)">Book</option>
                <option value="Furniture" id="#Furniture" onchange="show(this)">Furniture</option>
            </select>
        </fieldset>

        <br>
        <div class="subform-test-class">
        <fieldset id="#DVD" class="info-block">
            <label for="#DVD">Size (MB)</label>
            <input type="text" id="#DVD" name="dvdSize">
                <p>*Please provide size of the DVD (MB)</p>
        </fieldset>
        <br>
        <fieldset id="#Book" class="info-block">
            <label for="#weight" id="book">Weight (KG)</label>
            <input type="text" id="#weight" name="bookWeight">
                <p>*Please provide weight of the book in KG.</p>
        </fieldset>
        <br>

        <fieldset id="#Furniture" class="info-block">
            <label for="#height" id="height">Height</label>
            <input type="text" id="#height" name="fHeight">

            <label for="#width" id="width">Width</label>
            <input type="text" id="#width" name="fWidth">

            <label for="#length" id="length">Length</label>
            <input type="text" id="#length" name="fLength">
                <p>*Please provide size of the furniture in dimensions of HxWxL</p>
        </fieldset>
    </div>
    </form>

Im trying to create it dynamic so that when you select something else, the previous fieldset changes to new one and the last selection disappears. Nothing works with my code. I tried traditional JS – same results. I already put the div as display:none in CSS. Maybe my syntax is wrong?

$('body').on('change','##productType', function(){
    if($(this).val()=="DVD")
        $("#DVD").show();
    else
        $("#DVD").hide(); 
});

I keep getting “Unknown custom field” error trying to add a contact with custom field to SimpleTexting

Here’s my code:

app.post('/api/outgoing-from-ac', async (req, res, next) => {
    try {
        const {contact} = req.body;
        const {email, first_name, last_name, phone, tags} = contact;

        let response = await axios({
            method: 'post',
            url: 'https://app2.simpletexting.com/v1/group/contact/add',
            json: true,
            data: querystring.stringify({
                token: config.simple_texting.token,
                group: 'Registrants',
                phone,
                firstName: first_name,
                lastName: last_name,
                email,
                custom_tags: tags, // <--- This does not work!
            }),
            headers: {
                'content-type': 'application/x-www-form-urlencoded',
            },
        });

        console.log(response.data);

        res.json({
            status: 'OK',
        });
    } catch (error) {
        console.log(error);
        res.json({
            success: false,
            message: 'Error!',
        });
    }
});

So I’m trying to add contacts to a list in SimpleTexting using their API, along with tags with the other data, I removed all the unnecessary codes since everything else is working just fine.
When I try to add a contact without custom_tags, it adds, but when I use the custom_tags, it gives out the error { code: -611, message: 'Unknown custom field' }
This is what their documentation reads:

customField 
string
Any custom field of a contact, where customField` must be replaced with the actual custom field’s parameter.

For example, if you have a ‘Street address’ custom field, you would use the parameter ‘street_address’.

I tested customField, I tested object inside customField, I tested custom_tags, I tested tags, nothing is working. What is the issue here? How should it be coded?

HTML-To-Image doesn’t include images on mobile [duplicate]

I am trying to generate an image and download it to the client’s device when a button is clicked. The generateImage function is called on click. It works fine on a desktop browser and generates an image from the React component including all elements in the component. This component has some text an SVG component and a few images imported from a local directory. But the issue is, on mobile devices and safari desktops, it doesn’t include the images that are rendered in the component. Images are hosted locally, so it is not a CORS issue, also images are completely loaded to the component (I’ve checked this). Lastly, I tried converting images to base64 but still, they are not in the generated image. Here is the function:

import { toPng } from "html-to-image";
  
 const generateImage = () => {
    return new Promise((resolve, reject) => {
      dispatch({ type: "SHOW_TOOLTIP", payload: false });

      const node = document.getElementById("share-content");
      node.style.display = "block";

      const images = Array.from(node.getElementsByTagName("img"));
      const loadedImages = images.map((img) => {
        if (img.complete) return Promise.resolve();
        return new Promise((resolve, reject) => {
          img.onload = resolve;
          img.onerror = reject;
        });
      });

      Promise.all(loadedImages)
        .then(() => {
          return toPng(node);
        })
        .then((dataUrl) => {
          const link = document.createElement("a");
          link.download = "image.png";
          link.href = dataUrl;
          link.click();

          node.style.display = "none";
          dispatch({ type: "SHOW_TOOLTIP", payload: true });
          resolve();
        })
        .catch((error) => {
          console.error("oops, something went wrong!", error);
          node.style.display = "none";
          dispatch({ type: "SHOW_TOOLTIP", payload: true });
          reject(error);
        });
    });
  };


 

I want to ask a question I am struggling with, but I don’t have enough rep points to post [closed]

I am struggling with a regex problem, and I found a post that could be useful, but I do no have enough points to ask my question. How does one typically go about this? I apologise for this stupid question, but I am stuck.

My question is related to highlighting/bolding text (javascript/react) given a search term such as “a”.

I’ve tried working with regex solutions, but I’ve hit a wall.

Updating Google Maps Marker with new coordinates triggered by OnDragEnd

Very new to React (and JavaScript in general). I’m drawing a Google Maps map, setting some markers based on some objects. Works fine. However I’d like to, ultimately, update my object with the new coordinates if dragging the marker associated with the object. This because I need to update the entries in a DB later.

Help would be greatly appreciated. React/JS confuses me a lot initially. Thank you.

export default function MapGeo() {
    const { isLoaded } = useLoadScript({
        googleMapsApiKey: "secret",
    })

    if (!isLoaded) return <div>Loading...</div>;
    return <Map />;
}

// Dummy-data for testing purpose; should come from API
var dataArray = [
    { KeyId: 1, Latitude: 56.1065, Longitude: 10.20000, Address: "Street 1" },
    { KeyId: 2, Latitude: 56.1066, Longitude: 10.20010, Address: "Street 2" },
    { KeyId: 3, Latitude: 56.1067, Longitude: 10.20005, Address: "Street 3" },
    { KeyId: 4, Latitude: 56.1068, Longitude: 10.20010, Address: "Street 4" }
  ];

function Map() {

    // Center card using first array item
    const center = useMemo(() => ({lat: dataArray[0].Latitude, lng: dataArray[0].Longitude}), []);


    const [da, setDa] = useState(dataArray);


    return (
        <div>
        <h1>{title}</h1>
       
        <GoogleMap

            zoom = {18}
            center = {center}
            mapTypeId = {google.maps.MapTypeId.ROADMAP}
            
            mapContainerClassName = "map-container"
        >
             
            {dataArray.map(d => {
                return (
                    <Marker
                        position = { {lat: d.Latitude, lng: d.Longitude} }

                        name = {d.KeyId}
                        draggable = { draggable }
                        animation = { google.maps.Animation.DROP }
                        title = {
                            'Adresse: ' + d.Address + 'n'
                        }

                        // onDragEnd={(t, map, coord) => this.onMarkerDragEnd(coord, index)}
                        
                    />
                )
            })}         

        </GoogleMap>
        
        </div>
    );
}

Not really sure how I can accomplish this. Use OnDragEnd maybe? Was reading up on useState but had no joy with that.

Array comparison is always returning false in Angular Typescript

I am trying to compare 2 nested arrays but it is always returning false.

I want to do a comparison such that saleLineList in each saleBlock of this.saleBlockList is equal to the saleLineList in each saleBlock of saleBlockList.

Even if I modify the data it is still returning false. I have spent a lot of time on this but I am not able to figure out what I am doing wrong. Please help me. Thanks

let check = saleBlockList.every(item => this.saleBlockList.every(saleBlock => saleBlock.saleLineList == item.saleLineList)) 

console.log('check', check)

The given origin is not allowed for the given client ID, but only on Android usig chrome

I’m getting an error with GSI saying

The given origin is not allowed for the given client ID

However it’s only happening on Android. I have no idea why this is. Any ideas?

In Chrome on Windows and Mac it works fine. I’ve searched all over Google and read the documentation carefully through to find a solution for this, but so far I’m stuck.

async function initClient() {
  await google.accounts.id.initialize({
    auto_select: true,
    referrerPolicy: {
      policy: 'strict-origin-when-cross-origin'
    }
    client_id: CLIENT_ID,
    callback: creds => initTokenClient(creds)

  });
  google.accounts.id.prompt();
  google.accounts.id.renderButton(
    document.getElementById("buttonDiv"), {
      locale: "en"
    }
  );
}

function initTokenClient(creds) {
  client = google.accounts.oauth2.initTokenClient({
    client_id: CLIENT_ID,
    referrerPolicy: {
      policy: 'strict-origin-when-cross-origin'
    }
    scope: 'https://www.googleapis.com/auth/calendar.readonly 
                    https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/admin.directory.user',
    callback: (res) => checkAuth(res)
  });
  getToken();
}

function checkAuth(res) {
  if (res !== undefined) {
    access_token = res.access_token;
    listUpcomingEvents();
  } else {
    console.log("Could not auth");
  }
}

function getToken() {
  client.requestAccessToken();
}

function revokeToken() {
  google.accounts.oauth2.revoke(access_token, () => {
    console.log('access token revoked')
  });
}

Stacked column bar with line

Is it possible to show stacked col with 2 line graph?
While interacting with the combination of stacked column and line graphs, is it possible to show the change in each line graph, as we hide couple of elements(scale) from stacked column?

for more context please view this link
might help you understand
Thanks for the help

I tried looking for the example of such case but everywhere it only shows change in stacked column while line graph remains as it is

EROFS: read-only file system, open when trying to download a file from an S3 bucket with a lambda function

I want to be able to download a file from an aws lambda function.
For that I’ve come up with the following code:

export const downloadFile = async (fileType: FileType): Promise<FileEntry> => {
    const writeStream = fs.createWriteStream(path.join(__dirname, fileType.name))
    const readStream = s3Client.getObject({
        Bucket: process.env.FILE_UPLOAD_BUCKET,
        Key: fileType.key
    }).createReadStream()
        
    readStream.pipe(writeStream)

    return new Promise((resolve, reject) => {
        writeStream.on('finish', () => {
            writeStream.close()
            resolve({
                filename: fileType.uri,
                contentType: 'application/pdf',
                content: fs.readFileSync(fileType.uri),
                encoding: 'utf8'
            })
        })
        writeStream.on('error', (err) => {
            fs.unlink(fileType.uri, () => { reject(err) })
        })
    })
}

However it is not working, since I am getting the following error:

"EROFS: read-only file system, open '/var/task/api/controllers/Admin/filename.pdf'"

By the way this folder structure is the same I have in the controller I am using for handling this API call

JS events required to type any letter in google search bar

I want to create a test script which types letter h and it should show suggestions. But below code is doing nothing
I am trying this

// Find the search box element
let searchBox = document.querySelector(‘input[name=”q”]’);

// Create a KeyboardEvent for “keydown” event
let keyDownEvent = new KeyboardEvent(‘keydown’, {
key: ‘h’,
code: ‘KeyH’,
keyCode: 72,
view: window,
bubbles: true
});

// Dispatch the “keydown” event
searchBox.dispatchEvent(keyDownEvent);

// Create a KeyboardEvent for “keyup” event
let keyUpEvent = new KeyboardEvent(‘keyup’, {
key: ‘h’,
code: ‘KeyH’,
keyCode: 72,
view: window,
bubbles: true
});

// Dispatch the “keyup” event
searchBox.dispatchEvent(keyUpEvent);

Can you suggest if I am missing any other events or anything is wrong here.
I am using Chrome console to run this and getting true as response.

I found what events are hitting when we type any letter events are keyDown, KeyPress, inputTest, input & keyUp.

I tried all in once script & keyDown & keyUp as well. but Nothing worked

React doesn’t rerender when props are changing

In onClick I’m setting state value and sending this to child component as props, but child component is not rendering second time.

const onStatusChangeClick = async(toStatus, status) => {
  try {
    if (toStatus === "rejected" || toStatus === "internallyRejected") {
      setReviewForm(true);
      proceedToStatusChange = false;
    } else {
      proceedToStatusChange = true;
      setReviewForm(false)
    }

  } catch (error) {
    message.error("Status change failed");
  }
};

<Child showForm = {showForm}>

First time render It’s getting called but not second time

Angular dynamic accordion

I want to show my datas from my db with accordion using angular. ı dont use bootsrtap. ı don’t know how to do it ı found a documentation : https://www.npmjs.com/package/ng-dynamic-accordion?activeTab=readme about ng-dynamic-accordion but when ı try to npm i ng-dynamic-accordion ı get errors.

enter image description here

ı tried this :

listelehastalik(){

        for (let i =0; i<this.hastaHastalikList.length;i++){
            this.content+='<p-accordionTab header="Header I">n' +
                '                <div class=" col-12 md:col-6 lg:col-3">n' +
                '                    <h5 class="font-bold text-primary-700">Hastalık Adı</h5>n' +
                '                    <p>Hastalıkkkkkk Adı</p>n' +
                '                </div>n' +
                '                <div class=" col-12 md:col-6 lg:col-3">n' +
                '                    <h5 class="font-bold text-primary-700">Hastalık Tanımı</h5>n' +
                '                    <p>Hastalık Tnımı</p>n' +
                '                </div>n' +
                '                <div class=" col-12 md:col-6 lg:col-3">n' +
                '                    <h5 class="font-bold text-primary-700">Hastalık Belirtileri</h5>n' +
                '                    <p>Hastalık Belirtileri</p>n' +
                '                </div>n' +
                '                <div class=" col-12 md:col-6 lg:col-3">n' +
                '                    <h5 class="font-bold text-primary-700">Yapılması Gerekenler</h5>n' +
                '                    <p>Yapılması Gerekenler</p>n' +
                '                </div>n' +
                '                <div class=" col-12 md:col-6 lg:col-3">n' +
                '                    <h5 class="font-bold text-primary-700">Yapılmaması gerekenler</h5>n' +
                '                    <p>Yapılmaması gerekenler</p>n' +
                '                </div>n' +
                '            </p-accordionTab>';
        }
    }

but didint work