React Drop Down with select

could you suggest what I could change in this code or what would be a good practice to validate a React Select?

export const BaseDropDown = function ({options,label = 'apple',}) {

    const [isOpen, setIsOpen] = useState(true);
    const [selectedOption,setSelectedOption] = useState('apple')

    const handleSelectOption = (value) => {
        setSelectedOption(value)
        setIsOpen(true)
    }

    console.log(selectedOption)
    const toggleDropdown = () => setIsOpen(!isOpen)


    return (
        <label className="base-drop-down">
            <span>{label}</span>
            <i>
                <svg xmlns="http://www.w3.org/2000/svg" width="13.5" height="7.695" viewBox="0 0 13.5 7.695">
                    <g id="_001-arrow-down-sign-to-navigate" data-name="001-arrow-down-sign-to-navigate" opacity="0.71">
                        <path id="Path_26537" data-name="Path 26537" d="M6.751,104.836a.943.943,0,0,0,.668-.277l5.8-5.8a.945.945,0,0,0-1.337-1.337l-5.136,5.136L1.615,97.418A.945.945,0,0,0,.278,98.755l5.8,5.8A.943.943,0,0,0,6.751,104.836Z" transform="translate(-0.001 -97.141)" fill="#463518"/>
                    </g>
                </svg>
            </i>
            <div onClick={toggleDropdown}>{selectedOption}</div>
            <ul className={`${isOpen ? 'hidden' : ''}`}>
                {options.map(({option,id}) => {
                        return(
                            <li key={id}
                                onClick={(ev) => handleSelectOption(option)}>{option}</li>
                            )
                    })}
                </ul>
        </label>
    )
}

I have tried to obtain values from this dropdown and I succeeded, but I have the impression that it is not quite a good practice.

Recursively drawing tree using CSS

I am trying to recursively draw a tree based on a dataset. Each level 0 item is added a class category (which has bold text styling) , each level 1 is added group and level 2 is added leaf. This tree can be drawn up to two levels. But when I am recursively drawing the tree, all the levels get bold styling and mouse hover as well is applying to whole instead of each level.

Here is the sandbox that shows both the trees , one drawn using recursion other one is hardcoded using css: https://codesandbox.io/s/tree-compared-9s828h

Can someone tell me what is wrong in the recursive approach.

import React from "react";
import "./styles.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

const DrawnTree = ({ treeData }) => {
  const renderNode = (node, level) => {
    const hasChildren = node.categories && node.categories.length > 0;
    const isLeaf = !hasChildren;

    let categoryType = "";
    if (level === 0) {
      categoryType = "category";
    } else if (!hasChildren) {
      categoryType = "leaf";
    } else {
      categoryType = "group";
    }

    const onClickNode = () => {
      // Handle node click  here
    };

    return (
      <div
        className={`list-row level-${level} ${categoryType}`}
        onClick={onClickNode}
        key={`${node.key}`}
      >
        <div className="list-item-holder">
          {hasChildren && (
            <div className="list-item-expander-holder">
              <span
                className={`expand-collapse-icon ${isLeaf ? "" : "expand"}`}
              >
                <span className="collapse-icon">
                  <FontAwesomeIcon icon="caret-down" />
                </span>
                <span className="expand-icon">
                  <FontAwesomeIcon icon="caret-right" />
                </span>
              </span>
            </div>
          )}
          <div className="list-item-details-holder">{node.name}</div>
        </div>
        {hasChildren && (
          <div className="list-row-children">
            {node.categories.map((category) => renderNode(category, level + 1))}
          </div>
        )}
      </div>
    );
  };

  const renderTree = () => {
    return treeData.map((node) => {
      return renderNode(node, 0);
    });
  };

  return (
    <div className="tree-list-section">
      <div className="left-holder-bottom-list-section">{renderTree()}</div>
    </div>
  );
};

export default DrawnTree;

Access token not defined

I get the following error in res.console : “Uncaught (in promise) ReferenceError: access_token is not defined.” Apparently the token is not picked up, possibly because it is not global: if so, how do I make it global here?

Here a screenshot of the code.

I expect to be able to pick up and use the access token which was returned in a previous fetch in order to be able fetch other data.

How can I get a URL for all of the current google maps markers?

I have been searching everywhere and all forums/links I find link me to this old outdated list:

https://sites.google.com/site/gmapsdevelopment/

But I want the images at this link (most modern marker):

https://developers.google.com/static/maps/documentation/javascript/images/default-marker.png

How can I see all of the images that live here? I specifically would like to use the colored versions of the current red default marker.

example of the markers I am looking for:
enter image description here

javascript input text using .value is not working

I’m trying to fill out a user form using javascript, however when I use .value to change the element to the customer’s name it doesn’t work properly. The value change, however once I save the form, the value changed back to its original value. This is the piece of HTML where I’m targeting the customer’s name

<span class="next-input next-medium"><input placeholder="Name" height="100%" autocomplete="off" value="insert-customer-name" data-spm-anchor-id="a2g0o.placeorder.0.i5.f94f29fdF6dfJe"></span>

What I wrote is:

const inputElement = document.querySelector('.next-input.next-medium input');
inputElement.value = 'Customer Name';

I even tried with

const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true, view: window });
inputElement.dispatchEvent(clickEvent);

// Set the value of the input element to 'Customer Name'
inputElement.value = 'Customer Name';

However all the time, the value change to “Customer Name” and then as soon as I manually click on the input or save the form it changed back to ‘insert-customer-name’ which was the original value.

I would have used puppeteer, but I’m trying to build a chrome extension so I have to stick with javascript since puppeteer is not supported.

Could you please help me to solve it? thanks a lot in advance!

Fastify Response Validation not working as expected

I have recently upgraded fastify to v4, I am using its plugin @fastify-response-validation (latest version), recently I observed that keywords like “minLength”, “maxLength”, “enum”, “format” are not taking effect and incorrect responses are getting through.

While certain keywords like “required” are working as expected. I am not able to debug till now what has gone wrong in the process.

I am not using ajv-formats and ajv-errors as separate plugins. I believe these basic validations should work without these.

Please help. Thanks in advance.

  const server = fastify({
ajv: {
  customOptions: {
    allErrors: true,
    coerceTypes: "array",
    useDefaults: true,
    allowUnionTypes: true,
    formats,
  },
},
logger: true,
trustProxy: true,
exposeHeadRoutes: false,

});

server.register(fastifyResponseValidation, {
ajv: {
  strict: true,
  schemas,
  coerceTypes: false,
},

});

Google charts is not rendering properly in react js

I’m using react-google-charts for creating a Geo Chart.

Sometimes the chart renders, sometimes it doesn’t. When it renders, and I reload it disappears and doesn’t render again.

import React, { useState, useEffect } from 'react';
import {
  Box,
  Grid,
  TextField,
  IconButton,
  MenuItem,
  Dialog,
  DialogContent,
  Typography
} from '@mui/material';
import { MenuSharp } from '@mui/icons-material';
import Chart from 'react-google-charts';
// import { useBeforeRender } from 'src/hooks/useBeforeRender';

function GeoChart({ rows, config, onConfigChange }) {
  const [columns, setColumns] = useState();
  const [data, setData] = useState([[config?.keyColumn, config?.valueColumn]]);

  const options = {
    colorAxis: {
      minValue: 0,
      colors: config?.chartColors?.length > 0 && [config?.chartColors]
    }
  };

  useEffect(() => {
    let modifiedColumns = rows[0] && Object.keys(rows[0])?.map((row) => row);
    setColumns(modifiedColumns);
  }, [rows]);

  useEffect(() => {
    let modifiedData = rows?.map((row) => {
      return [row[config?.keyColumn], row[config?.valueColumn]];
    });
    setData((prevValue) => [prevValue[0], ...modifiedData]);
  }, [rows, config?.keyColumn, config?.valueColumn]);

  return (
    <Box sx={{ width: '100%', height: '100%', p: 1 }}>
      <Box
        sx={{
          height: '90%',
          width: '100%',
          display: 'flex',
          alignItems: 'center',
          flexDirection: 'center',
          px: 1,
          mt: 2
        }}
      >
        {data?.length < 0 ? (
          'Invalid Data'
        ) : (
          <Chart
            width={'100%'}
            height={'100%'}
            chartType="GeoChart"
            data={data}
            options={options}
            mapsApiKey="API KEY"
          />
        )}
      </Box>
    </Box>
  );
}

export default GeoChart;

I’ve checked data, options and config are being set properly everytime. But it still it doesn’t work.

ScrollView with position absolute is not scrolling in android [react native]

I want to make dropdown view using scrollview in react native, but scrollview is not scrolling in android while its position is absolute, in IOS it is scrolling like a charm.

This is my code

   <View style={{ flexDirection: 'row', zIndex: 1 }}>
        <TouchableOpacity
            style={styles.contryCode}
            onPress={()=>setVisible(prev=>!prev)}
        >
            <Text style={styles.selectedCode}>{code}</Text>
            <Icon name={visible ? 'up' : 'down'} size={15} color='#000' />
        </TouchableOpacity>
        {visible ? <CodeList /> : null}
    </View>
const CodeList = () => {
    return (
        <ScrollView
            style={styles.codeList}
            showsVerticalScrollIndicator={false}
        >
            {codes.map((item: any, index: number) => {
                return (
                    <TouchableOpacity key={index} onPress={() =>     handleSelectCountry(item?.phonecode)}>
                        <Text style={styles.codeText}>{item.phonecode}</Text>
                    </TouchableOpacity>
                );
            })}
        </ScrollView>
    )
 }

I also tried wrapping Scrollview with posotion:'relative' in a View with position:'absolute', but it did not worked.

Compare and merge array of objects in Javascript if first object does not contain objects from second array

I want to compare and add elements from second array into first whichever objects or nested objects are not present into first array of object.

`let obj1 = [
{
“_id”: “63eb2c20fd30492730e203bb”,
“name”: “name 01”,
“isActive”: true,
“locations”: [],
“code”: “888888”
},
{
“_id”: “638482b90b6d64eccee23be7”,
“name”: “name 02”,
“isActive”: true,
“locations”: [
{
“primaryContact”: {
“name”: “name 03”,
“designation”: “”,
“email”: “”,
“phone”: “+1 845566 556”,
“isBilling”: true
},
“_id”: “638484359f153cecd64212a8”
},
{
“primaryContact”: {
“name”: “name 04”,
“designation”: “”,
“email”: “”,
“phone”: “(000) 000-0000”,
“isBilling”: true
},
“_id”: “638484359f153cecd6464789”
},
{
“primaryContact”: {
“name”: “name 05”,
“designation”: “”,
“email”: “”,
“phone”: “(000) 000-0000”,
“isBilling”: true
},
“_id”: “638484359f153cecd65843a8”
}
]
}
]

let obj2=[
{
“_id”: “63eb2c20fd30492730e203bb”,
“name”: “name 01”,
“isActive”: true,
“locations”: [],
“code”: “888888”
},
{
“_id”: “638482b90b6d64eccee23be7”,
“name”: “name 02”,
“isActive”: true,
“locations”: [
{
“primaryContact”: {
“name”: “name 03”,
“designation”: “”,
“email”: “”,
“phone”: “+1 845566 556”,
“isBilling”: true
},
“_id”: “638484359f153cecd64212a8”
},
{
“primaryContact”: {
“name”: “name 08”,
“designation”: “”,
“email”: “”,
“phone”: “(000) 000-0000”,
“isBilling”: true
},
“_id”: “638484359f153ferg52a8”
}
]
},
{
“_id”: “63eb2c20hijkl920e203bb”,
“name”: “name 10”,
“isActive”: true,
“locations”: [],
“code”: “888888”
}
]`
We can see that in obj2 there is one child object which is not present and one object which is not present in obj1.

Expecteed Output:
let output = [ { "_id": "63eb2c20fd30492730e203bb", "name": "name 01", "isActive": true, "locations": [], "code": "888888" }, { "_id": "638482b90b6d64eccee23be7", "name": "name 02", "isActive": true, "locations": [ { "primaryContact": { "name": "name 03", "designation": "", "email": "", "phone": "+1 845566 556", "isBilling": true }, "_id": "638484359f153cecd64212a8" }, { "primaryContact": { "name": "name 04", "designation": "", "email": "", "phone": "(000) 000-0000", "isBilling": true }, "_id": "638484359f153cecd6464789" }, { "primaryContact": { "name": "name 05", "designation": "", "email": "", "phone": "(000) 000-0000", "isBilling": true }, "_id": "638484359f153cecd65843a8" }, { "primaryContact": { "name": "name 08", "designation": "", "email": "", "phone": "(000) 000-0000", "isBilling": true }, "_id": "638484359f153ferg52a8" } ] }, { "_id": "63eb2c20hijkl920e203bb", "name": "name 10", "isActive": true, "locations": [], "code": "888888" } ]

My program won’t store cookies. [Kind of duplicate]

I am trying to do cookies in JavaScript but when I run the snippet from W3 in Visual Studios but it won’t work. I’ve even tried the one from [Mozilla] (https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) too.

I’ve ran the snippet several times, and no such luck. I’ve tried it on a new tab. Still have nothing. I have tried setting document.cookie to something like what mozilla says you can do but it doesn’t work.

Change the colour of p-dropdown items based on a Boolean value

I want to change the background colour of my primeng drop-down items which is dependent on a boolean value that I’m getting from an api and pushing it into a array i.e users

I have a array of objects users which contains 3 fields.
Response of the api is:

users=[{user_name:john.doe,user_id:'J012', is_promoted:true},{user_name:jane.doe,user_id:'J013', is_promoted:false}]
So I was trying to map the users array to get the is_promoted
users.map(u=>u.is_promoted);

If is_promoted is true then the background colour of p-dropdown-items must change to a certain colour.I’m not able to achieve this. Should I try [styleClass]?
CSS:

:host ::ng-deep.p-dropdown-items{
background:darkgrey
}

HTML

<p-dropdown [options]=users optionlabel="user_name" optionvalue="user_id" 
[ngStyle]="{'highlight':users.is_promoted==true}"[(ngModel)]="selectedValue> //Gives an error

I’m able to select the value here. But I need to change the background colour of the dropdown element based on the boolean value. How to approach this?

Structuring JSON object for looped component with Handlebars (HTML)

I’ve recently started using Handlebars and have the following HTML template:

    {{#each this.level3}}
    <div class="expanded-view" data-cmp-src="{{data-cmp-src}}">
      <div class="d-flex justify-content-between heading">
        <h4>Heading that should be the same for all children</h4>
        <button>Likewise for button text</button>
      </div>
      <div class="d-flex flex-wrap content-panel">
        <figure class="l3-item">
          <a href="#"
            ><img class="content-square" src="{{imgSrc}}" alt="{{altText}}"
          /></a>
          <figcaption>{{caption}}</figcaption>
        </figure>
      </div>
    </div>
    {{/each}}

It’s a basic component that displays a heading, button and then an image with a caption.

I’m using a JSON object to iterate through my items but am struggling to get the correct format.

The use of data-bs-target and data-cmp-src ensure the correct options are shown when they’re associated element is selected (logic handled out of snippet).

What I’d like to do however is structure my JSON in the correct way so that multiple images/captions can be returned when the data-cmp-src is matched, which also means they can share the same title and button text. I know the JSON object formatting isn’t correct but any tips would be appreciated.

Summary: I want child objects to share the same heading, btnText, data-properties. (Currently I can only show one image/caption).

    "level3": [{
    {
      "heading": "Option 1 View heading",
      "btnText": "Option 1 View btn text",
      "data-bs-target": "#historyCollapseOneChild",
      "data-cmp-src": "historyL3Child",
      {
        "imgSrc": "../../assets/images/mega-menu/hegra.png",
        "caption": "the first image in view 1"
      },
      {
        "imgSrc": "../../assets/images/mega-menu/hegra.png",
        "caption": "the second image in view 2"
      },
        },
    {
      "heading": "Option 2 View heading",
      "btnText": "Option 2 View btn text",
      "data-bs-target": "#historyCollapseOneChild",
      "data-cmp-src": "historyL3Child",
      {
        "imgSrc": "../../assets/images/mega-menu/hegra.png",
        "caption": "the first image in view 2"
      },
      {
        "imgSrc": "../../assets/images/mega-menu/hegra.png",
        "caption": "the second image in view 2"
      },
        }
    ]

Please someone help me with the google analytics documentation for js?

I need some help with javascript and google API analytics

I’m trying to use google analytics database to pick how much people are online and where they came from, but i’m too lost in the documentation. My most problematic thing is that i can’t understand how can i pick the data and push it to my website. how can i do it just using javascript? Can someone please link me where is what i’m talking about at the documentation? Because i’m too lost in that.

Automatically Copy Text on Web Page

I’m needing help on how I can make something that will automatically copy certain text on a website. There is a question and below the question is 4 possible answers, and they are all A, B, C, and D. I want to make something that will copy the question, along with the answers all together. Thanks in advance, this will help me very much if I can get it to work.
I think it might be easy to make by copying the text contained in the div class variables because the question has its own and each of the answers have their own. I just need help creating it and making sure it will work. Thanks in advance!

I haven’t tried anything yet because I am still an amateur at coding, but I am willing to do whatever is needed to help make this or get it to work.