Arguments Object

i’m currently learning js and need to pass a test, every requirement checks out besides “should work on an arguments object”. I noticed that when I take out the Array.isArray() part of the code, it works. However then I wont pass the “return an empty array if array is not an array” part of the test.

we are allowed to ask for help on stackoverflow so I would appreciate the help. thanks 🙂

this is my code:

// Return an array with the first n elements of an array.
// If n is not provided return an array with just the first element.
_.first = function (array, n) {
  var resultArray = [];
  if (Array.isArray(arguments[0]) !== true){
    return []} 
  else if (arguments[1] > arguments[0].length){
  return arguments[0]
 } else if (typeof arguments[1] !== "number" || arguments[1] == 0 || arguments[1] < 0){
  resultArray.push.call(resultArray, arguments[0][0])
  return resultArray
 } else {
 for (var i = 0; i < arguments[1]; i++)
 resultArray.push.call(resultArray, arguments[0][i]);
 return resultArray;
}
};

html adding a comma to user inputs on a form

I have a html form taking user inputs as per below. However, when the form submits, I get the data in the back-end in the below format. Notice that the make, model, and engine capacity data has a comma and brackets yet the other fields are okey. I really do not know why this is the case. Anyone help me fix this.

Description             Details Provided
MAKE:                    ('MAZDA',)
MODEL:                   ('ATENZA',)
TRIM DETAILS:             standard
ENGINE CAPACITY (cc):     (2000,)
FUEL TYPE:                PETROL
MILEAGE (km):             120000
TRANSMISSION:             AUTOMATIC
YEAR OF MANUFACTURE:      2009

Prevent active accordion item from closing on click

i’m working on a design for a site, but i’m super new to any kind of coding, so there’s a lot that i don’t know the answer to (and haven’t been able to find yet).

currently, i’d like to know if it’s possible, with the code i currently have, to prevent the active accordion item/panel from closing when the header is clicked.

here’s the relevant part of my current code:

var acc = document.getElementsByClassName("accordionHeader");
var panel = document.getElementsByClassName('accPanel');

for (var i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    var setClasses = !this.classList.contains('open');
    setClass(acc, 'open', 'remove');
    setClass(panel, 'open', 'remove');
    if (setClasses) {
      this.classList.toggle("open");
      this.nextElementSibling.classList.toggle("open");
    }
  }
}

function setClass(els, className, fnName) {
  for (var i = 0; i < els.length; i++) {
    els[i].classList[fnName](className);
  }
}
document.getElementById("defaultOpen").click();
.accordionHeader {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s;
}

.accPanel {
  padding: 0 18px;
  background-color: white;
  display: none;
  overflow: hidden;
  transition: max-height 0.5s ease-out;
}

.open {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <title>polka time</title>
</head>

<body>
  <div>
    <button class="accordionHeader" id="defaultOpen">section 1</button>
    <div class="accPanel">
      At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
      animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda
      est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis
      voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
    </div>

    <button class="accordionHeader">section 2</button>
    <div class="accPanel">
      At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
      animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda
      est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis
      voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
    </div>
    <button class="accordionHeader">section 3</button>
    <div class="accPanel">
      At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
      animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda
      est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis
      voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
    </div>
  </div>

  <script src="character page js.js" type="text/javascript"></script>
</body>

</html>

if at all possible i’d like to not change too much about the code, since i only just got it working (more or less). i’m sure my code’s a total mess though since i’ve mainly been copying off tutorials the whole time.

also if there’s a good way to get the accordion to animate that would be a bonus.

How to run an async function in js with timeouts (for rate limiting)

I’m designing a system where a user will interact with my RESTful API through JS, and will replace the ts html element with a different SVG if the returned answer is true. If the API call returns false, the JS should wait for 5 seconds, before retrying the API call. again, if the API call returns true, the SVG will be changed, and the function will stop calling the API. How can I have the function “sleep” for 5 seconds before running again, and ending the function if the returned API call is true?

Code:

async function getTransaction(){
var lookup = $("meta[name='lookup']").attr("content");  
axios.get('http://127.0.0.1:5000/client_api/transaction_status/' + lookup) 
.then(function (response) {
    var tStat = response.data.transactionStatus;
    console
    if(tStat){
      document.getElementById("ts").innerHTML = 'drawing the new svg and replacing the old one'
      console.log('transaction_found')
    }
    else if(!tStat){
      console.log("transaction not found")
    }
    else{
      console.log("error")
    }
  });
  }console.log("hello"); while(true){setTimeout(getTransaction,5000);}

javascript: backgroundColor not working on a element

im trying to change the background color of this <li> element but I’m getting error Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor'). i have been trying to fix this for hours but nothing works. As you can see, I want it to change the background color of the rows element in an if statement and below is my JS code.

var vals;
var rows;
var sum;
var rowsarr = [];
var avg;

function obser1() {
    const trades = document.querySelector('.scrollbar-dark');
    const observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            if (mutation.addedNodes.length) {
                vals = [...mutation.addedNodes[0].querySelectorAll("span")].map(span => span.textContent);
                if (vals.length == 4) {
                    rows = vals[2];
                    rowsarr.push(rows);
                }
                if (vals.length == 3) {
                    rows = vals[1];
                    rowsarr.push(rows);
                }
                console.log(mutation.addedNodes[0]);
                console.log(rows+"  rows");
            }
        })
        function arraysum(x, y) {
            return parseFloat(x) + parseFloat(y);
        }
        sum = rowsarr.reduce(arraysum);
        console.log(rowsarr.length + "  length");
        if (rowsarr.length >= 100 && rowsarr.length<105) {
            avg = sum / 50;
            console.log("average is  " + avg);
        }
        /*This is the problem*/
        if (rows > avg) {
            console.log(rows + "  large" + "  average  " + avg);

            rows.style.backgroundColor = "white";
        }
    });
    observer.observe(trades, {
        childList: true,
        subtree: true,
        attributes: true,
        characterData: true
    })
   
}

window.setTimeout(btn4, 1000);
window.setTimeout(obser1, 1700);

Google Firebase httpsCallable raising net::ERR_NAME_NOT_RESOLVED

I am running into net::ERR_NAME_NOT_RESOLVED when calling the API of my firebase project. I have tried using multiple devices, two internet connections, a VPN, Linux, macOS, Windows 11 to rule out any errors caused by my devices. When navigating to the API link on my browser it does not timeout, and I am provided with a response. The issue seems to be when using the httpsCallable function provided by Firebase. No logs of the function being called are present on firebase outside of navigating to it in a browser.

Here is my code:

const functions = firebase.functions
console.log(functions)
const loginWithCode = httpsCallable(functions, 'loginWithCode')

loginWithCode(loginPayload)
    .then((result) => {
        console.log(result)
    })
    .catch((error) => {
        console.log("ERROR CAUGHT HERE")
        console.log(error)
    });

The output from my browser console:

service.ts:206 POST https://us-central1-%22crowd-pleaser-75fd7%22%2C.cloudfunctions.net/loginWithCode net::ERR_NAME_NOT_RESOLVED
App.tsx:79 ERROR CAUGHT HERE
App.tsx:80 FirebaseError: internal

The result from directly inputting the link on the firebase web interface:

{"error":{"message":"Bad Request","status":"INVALID_ARGUMENT"}}

Is there something I am missing that is creating this issue? I have scoured the internet, and StackOverflow looking for an answer, and all solutions provided have not worked. The method implemented is exactly how it is done on the Firebase docs here

How to get different images to display when clicking on a radio button using JavaScript?

I have been trying for days to figure this out. I need to click on a radio button and have the image change. For example if I click on the golden gate bridge radio button I need it to switch the image to the picture of the bridge. So far I can only get it to click on the image and then the image changes but that is not what I want to do. I have tried many different ways and nothing works. I am new to JavaScript.

<!DOCTYPE html>
<html>
<body>
<!--Statue of Liberty image-->
<img id="statue" onclick="changeImage()" 
src=
'https://www.history.com/.image/ar_4:3%2Cc_fill%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_1
200/MTY1MTc1MTk3ODI0MDAxNjA5/topic-statue-of-liberty-gettyimages-960610006-promo.jpg' 
width="300">


<p>Click the picture to change image.</p>

<script>
//Functon that changes mage when clicking on the image
function changeImage() {
  var image = document.getElementById('statue');

  if (image.src.match("statue")) {
  image.src=

 'https://www.history.com/.image/ar_4:3%2Cc_fill%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_1200/MTY1MTc3MjE0MzExMDgxNTQ1/topic-golden-gate-bridge-gettyimages-177770941.jpg';
  } 
  else if (image.src.match("bridge"))
  {
    image.src = "https://media-cldnry.s-nbcnews.com/image/upload/newscms/2020_26/3392557/200625-mount-rushmore-al-0708.jpg";
}
}
</script>
<!-- Radio buttons-->
    <form>
    <input type="radio" id = "statue-button" name = "landmark" checked value="statue"onClick= ('toggleImage')>Statue of Liberty<br>
    <input type="radio" id = "bridge-button" name="landmark" value="bridge">Golden Gate Bridge<br>
    <input type="radio" id = "rushmore-button" name="landmark" value="rushmore">Mount Rushmore<br>
    </form>

</body>
</html>

Filter through nested arrays and return objects with matching categories

I’m using react+ nextJS and grabbing static objects, “posts”. The goal is to create a “related posts” component on each post which grabs three posts that contain at least one of the categories. Here’s what it looks like when I run a map on AllPosts (I trimmed it down so it’s easier to read):

const allPosts = getAllPosts(['title', 'categories'])
[{
  title: 'Black History Month: A History in Black Cinematography',
  categories: [ 'education' ]
}
{
  title: 'New Kid on the Block',
  categories: [ 'announcements', 'new hires' ]
}
{
  title: 'Olivia Boldt: Bol(d)ting Into the Bakery',
  categories: [ 'announcements', 'new hires' ]
}
{
  title: 'PDF Presets in Adobe Illustrator. Which one should you use?',
  categories: [ 'Research', 'education' ]
}
{
  title: 'Pixel Bakery does XYZ',
  categories: [ 'press & media', 'announcements' ]
}
{
  title: 'Recipe for Success: Mix Adaptability and Confidence (together, in a medium sized bowl)',
  categories: [ 'editorial', 'second cat', 'third cat' ]
}
{
  title: 'Samee Callahan: A Winding Path to Excitement',
  categories: [ 'announcements', 'new hire' ]
}
{
  title: 'Sophia Stueven’s Favorite Way to Breathe',
  categories: [ 'announcements', 'new hires' ]
}]

So far, I can get it to match posts that have the same [0] category, but I can’t wrap my brain around how to compare all of them:

const allPosts = getAllPosts(['title', 'categories'])
const SearchCat = post.categories[0]
const matchingPosts = allPosts.filter((item) => item.categories[0] === SearchCat)
console.log(matchingPosts)

yields:

  [{
    title: 'An Introduction to our Technology Stack',
    categories: [ 'announcements', 'new hire' ]
  },
  {
    title: 'New Kid on the Block',
    categories: [ 'announcements', 'new hires' ]
  },
  {
    title: 'Olivia Boldt: Bol(d)ting Into the Bakery',
    categories: [ 'announcements', 'new hires' ]
  },
  {
    title: 'Samee Callahan: A Winding Path to Excitement',
    categories: [ 'announcements', 'new hire' ]
  },
  {
    title: 'Sophia Stueven’s Favorite Way to Breathe',
    categories: [ 'announcements', 'new hires' ]
  }]

How do I go about adding another filter layer that doesn’t care about the position the category match is in and only require one of them to match?

Web App crashes when trying to plot a timeline chart in Apexcharts with Vue 3

I have a web application where I am using ApexCharts with Vue 3 to plot some graphics. I didn’t have any trouble using the scatter plot, but when I try to plot a timeline like this example of the website, it completely crashes and I don’t know why. maybe I am doing something wrong, but I can’t see any error. I would appreciate a lot if you can give me some help because it is important!

I attach here the code of the view:

<template>
    <apexchart type="rangeBar" height="350" :options="chartOptions" :series="series"></apexchart>
</template>
<script>
import axios from "../../../services/api.js";

export default {
  data() {
    return {
        chartOptions: {
            chart: {
                type: 'rangeBar'
            },

            plotOptions: {
                bar: {
                    horizontal: true,
                }
            },

            fill: {
              type: 'solid'
            },

            xaxis: {
              type: 'datetime'
            },
        },
        series: [
          {
            name: 'Prueba',
            data: [
               {
                  x: 'Code',
                  y: [
                    new Date('2019-03-02').getTime(),
                    new Date('2019-03-04').getTime()
                  ]
                },
                {
                  x: 'Test',
                  y: [
                    new Date('2019-03-04').getTime(),
                    new Date('2019-03-08').getTime()
                  ]
                },
                {
                  x: 'Validation',
                  y: [
                    new Date('2019-03-08').getTime(),
                    new Date('2019-03-12').getTime()
                  ]
                },
                {
                  x: 'Deployment',
                  y: [
                    new Date('2019-03-12').getTime(),
                    new Date('2019-03-18').getTime()
                  ]
                },
            ]
          },
      ], //end series
    }; //end return
  }, //end data

}
</script>
<style scoped>

</style>

Best way of grouping array objects by multiple values in javascript.ES6

Good day developers Im wondering how I could group an array of objects of different values in specific sub-groups , where in each sub-group my contain objects with specific values according to the key queried.

My array would be something like this

    {
        'make': 'audi',
        'model': 'r8',
        'year': '2012'
    }, {
        'make': 'audi',
        'model': 'rs5',
        'year': '2013'
    }, {
        'make': 'ford',
        'model': 'mustang',
        'year': '2012'
    }, {
        'make': 'ford',
        'model': 'fusion',
        'year': '2015'
    }, {
        'make': 'kia',
        'model': 'optima',
        'year': '2012'
    },
];

And i would like to gather by the key make in a subgroup of name 2nd_class all objects that in the key make, had as value kia or ford, gathering the others in a group 1rst_class
Having as result an object like :

[
   2nd_clas:[
        {
        'make': 'ford',
        'model': 'mustang',
        'year': '2012'
        }, 
        {
        'make': 'ford',
        'model': 'fusion',
        'year': '2015'
        }, 
        {
        'make': 'kia',
        'model': 'optima',
        'year': '2012'
        },
   ] ,
   1rst_class:[
        {
        'make': 'audi',
        'model': 'r8',
        'year': '2012'
        }, 
        {
        'make': 'audi',
        'model': 'rs5',
        'year': '2013'
        }
   ]
]

All the examples on the web always refer to grouping by key and one specific value ….
Any help would be amazing.Thanks in advance

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.jpg”

I am trying to create an api in my server.js file for a react app. I connected the server and as soon as I imported data.js and set it to the api/products page it gave me the error.

    import express from 'express';
    import data from '../src/data.js';

    const app = express();

    app.get('/api/products', (req, res) => {
        res.send(data.products);
});

app.get('/', (req, res) => {
    res.send('Server is ready');
});

app.listen(5000, () => {
    console.log('Serve at http://localhost:5000');
});

How to Render Fetched Object Items in React Component

How do I render an object that I’ve fetched in React?

Here is my code:

const PrayerTimesByCity = () => {
  // Initiate array for fetching data from AlAdhan API
  const [data, setPrayerTimes] = useState({});

  useEffect(() => {
    fetch(
      "http://api.aladhan.com/v1/timingsByCity?city=Helsingborg&country=Sweden&method=0"
    )
      .then((resp) => resp.json())
      .then((data) => setPrayerTimes(data));
  }, []);

  console.log(data);

  return <div> // Here is where I want my objects to return </div>;
};

Here is what the fetched data returns:

{
  "code": 200,
  "status": "OK",
  "data": {
    "timings": {
      "Fajr": "06:42",
      "Sunrise": "09:00",
      "Dhuhr": "12:13",
      "Asr": "13:17",
      "Sunset": "15:27",
      "Maghrib": "16:00",
      "Isha": "17:29",
      "Imsak": "06:32",
      "Midnight": "00:13"
    }
}

I want to extract “data” and then “timings” and then each respective item and its key. How do I do this in my return statement in my component?

Thanks for any answer in advance

make a function globally available via webpack

I have a .ts file that contains a function, and I want to compile this file into .js file via webpack to be loaded in index.html.

I need this function to be globally available in index.html

index.html

<script src="./myfile.js"></scrit>
<script>
  console.log(myfunction);
// ----> error: myfunction is not defined
</scrit>


<script type="module">
  import myfunction from './myfile'
  console.log({myfunction})
// ----> error: requested module './myfile.js' does not provide an export named 'myfunction'
</script>

myfile.ts

export myfunction = function(){}

webpack.config

{
    mode: 'development',
    devtool: false,
    target: [ 'web', 'es5' ],
    profile: false,
    resolve: {
      roots: [Array],
      extensions: [Array],
      symlinks: false,
      modules: [Array],
      mainFields: [Array],
      plugins: [Array],
      alias: [Object]
    },
    resolveLoader: { symlinks: true, modules: [Array] },
    context: '/home/sh_eldeeb_2010/@eng-dibo/dibo/projects/ngx-cms',
    entry: {
      main: [Array],
      'polyfills-es5': [Array],
      polyfills: [Array],
      styles: [Array],
      scripts: './scripts.ts'
    },
    output: {
      clean: true,
      path: './dist',
      publicPath: '',
      filename: '[name].js',
      chunkFilename: '[name]-es2015.js',
      crossOriginLoading: false,
      trustedTypes: 'angular#bundler',
      library: undefined,
      libraryTarget: 'commonjs2'
    },
    watch: false,
    watchOptions: { poll: undefined, ignored: '**/$_lazy_route_resources' },
    performance: { hints: false },
    ignoreWarnings: [
      /System.import() is deprecated and will be removed soon/i,
      /Failed to parse source map from/,
      /Add postcss as project dependency/
    ],
    module: {
      strictExportPresence: true,
      rules: [Array],
      noParse: //native-require.js$/
    },
    experiments: { syncWebAssembly: true, asyncWebAssembly: true },
    cache: false,
    optimization: {
      minimizer: [Array],
      moduleIds: 'deterministic',
      chunkIds: 'deterministic',
      emitOnErrors: false,
      runtimeChunk: 'single',
      splitChunks: [Object]
    },
    plugins: [
      [ContextReplacementPlugin],
      [DedupeModuleResolvePlugin],
      [ProgressPlugin],
      [LicenseWebpackPlugin],
      [CommonJsUsageWarnPlugin],
      [AnyComponentStyleBudgetChecker],
      [Object],
      [MiniCssExtractPlugin],
      SuppressExtractedTextChunksWebpackPlugin {},
      [NgBuildAnalyticsPlugin],
      [AngularWebpackPlugin],
      [FilterErrors]
    ],
    node: false,
    stats: {
      all: false,
      colors: true,
      hash: true,
      timings: true,
      chunks: true,
      builtAt: true,
      warnings: true,
      errors: true,
      assets: true,
      cachedAssets: true,
      ids: true,
      entrypoints: true
    },
    externals: []
  },
  entry: {
    myfile: './myfile.ts'
  }
}

dropdown list displaying problems

I have 2 problems in my code , as you see I have a navbar that contain 6 items 2 of them should display a dropdown list when clicked .

I was able to make them display a dropdown list but there is a problem .

problem 1 : when I click on on of the 2 items both drop down list shows up , but what i want is that each item shows its dropdown list , plus I want when clicking outside the list for it to close.

problem 2 : when clicking on the other 4 items there is a path that i put to them , but it seem to work with the two item that shows a dropdown list , and i dont want that i want them with no path .

this is my navitem.js :

export const navItems = [
 {
      id: 1,
      title: "mybook",
      path: "./mybook",
      cName: "navitem",
    },
    {
      id: 2,
      title: "mylab",
      path: "./mylab",
      cName: "navitem",
    },
    {
      id: 3,
      title: "marks",
      path: "./marks",
      cName: "navitem",
    },
    {
      id: 4,
      title: "trash",
      path: "./trash",
      cName: "navitem",
    },
    {
        id: 5,
        title: "mywork",
        path: "./mywork",
        cName: "navitem",
      },
      {
        id: 6,
        title: "set",
        path: "./set",
        cName: "navitem",
      },
  ];
  
  export const mybookDropdown = [
    {
      id: 1,
      title: "fav",
      path: "./fav",
      cName: "submenu-item",
    },
    {
      id: 2,
      title: "continue",
      path: "./continue",
      cName: "submenu-item",
    },
  ];
  export const mylabDropdown = [
    {
      id: 1,
      title: "dailycheck",
      path: "./dailycheck",
      cName: "submenu-item",
    },
    {
      id: 2,
      title: "recommendation",
      path: "./recommendation",
      cName: "submenu-item",
    },
    {
        id: 3,
        title: "popular",
        path: "./popular",
        cName: "submenu-item",
      },
  ]; 

and here is my Dropdown.js :

import React, { useState } from "react";
import { mybookDropdown , mylabDropdown } from "./NavItems";
import { Link } from "react-router-dom";
import "./Dropdown.css";

function Dropdown() {
  const [dropdown, setDropdown] = useState(false);

  return (
    <>
      <ul
        className={dropdown ? "mybook-submenu clicked" : "mybook-submenu"}
        onClick={() => setDropdown(!dropdown)}
      >
        {mybookDropdown.map((item) => {
          return (
            <li key={item.id}>
              <Link
                to={item.path}
                className={item.cName}
                onClick={() => setDropdown(false)}
              >
                {item.title}
              </Link>
            </li>
          );
        })}
      </ul>
      <ul
        className={dropdown ? "mylab-submenu clicked" : "mylab-submenu"}
        onClick={() => setDropdown(!dropdown)}
      >
        {mylabDropdown.map((item) => {
          return (
            <li key={item.id}>
              <Link
                to={item.path}
                className={item.cName}
                onClick={() => setDropdown(false)}
              >
                {item.title}
              </Link>
            </li>
          );
        })}
      </ul>
    </>
  );
}

export default Dropdown;

lastly here is what I added to the navbar.jsx :

import { navItems } from "./NavItems";
import Dropdown from "./Dropdown";

export default function navbar() {
  const [dropdown, setDropdown] = useState(false);

 return (
<ul className={[styles.navitem]}>
              {navItems.map((item) => {
                if (item.title == "mybook")
                return(
                  <li key={item.id} className={item.cName}
                    onClick={() => setDropdown(true)}
                  >
                    <Link to={item.path}>{item.title}</Link>
                  </li>
                );
                else if (item.title == "mylab")
                return(
                  <li key={item.id} className={item.cName} 
                    onClick={() => setDropdown(true)}
                  >
                    <Link to={item.path}
                    >{item.title}</Link>
                  </li>
                );
                return(
                  <li key={item.id} className={item.cName}>
                    <Link to={item.path}>{item.title}</Link>
                  </li>
                );
              }
              )}
            { dropdown && <Dropdown />}
            </ul>
 );
}