Menu content display issue

I created a menu with section and courses; but the section-labels are repeating.

I would like all courses with the same section to be displayed on a single section lable.

Please see code and screenshot.

<Menu

                            defaultSelectedKeys={[clicked]}
                            inlineCollapsed={collapsed}
                            style={{ height: "100vh", overflow: "scroll" }}
                            mode="inline"
                        >

                            {course.lessons.map((lesson, index) => (

                                <SubMenu
                                    title={lesson.section}>
                                    <ItemGroup
                                        key={index}>

                                        <Item
                                            onClick={() => setClicked(index)}
                                            key={index}
                                            icon={<Avatar>{index + 1}</Avatar>}
                                        >

                                            {lesson.title.substring(0, 30)}
                                            {" "}
                                            {completedLessons.includes(lesson._id) ? (
                                                <CheckCircleFilled
                                                    className="float-end text-primary ml-2"
                                                    style={{ marginTop: "13px" }}
                                                />
                                            ) : (
                                                <MinusCircleFilled
                                                    className="float-end text-danger ml-2"
                                                    style={{ marginTop: "13px" }}
                                                />
                                            )}
                                        </Item>

                                    </ItemGroup>
                                </SubMenu>
                            ))}
                        </Menu>

Screenshot of the Menu

enter image description here

can a string be equal to a number


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Using Conditional Statements</title>
<link href="../_css/site.css" rel="stylesheet">
<script>
var luckyNumber = prompt('What is your lucky number?','');


</script>
</head>

<body>
<div class="wrapper">
    <header>
    JAVASCRIPT <span class="amp">&amp;</span> jQUERY: THE&nbsp;MISSING&nbsp;MANUAL
  </header>
    <div class="content">
        <div class="main">
<h1>Using Conditional Statements</h1>
        <script>
        if (luckyNumber == 7 ) {
            document.write("<p>Hey, 7 is my lucky number too!</p>");
        } else if (luckyNumber == 13 || luckyNumber == 24) {
            document.write("<p>Wooh. " + luckyNumber + "? That's an unlucky number!</p>");
        } else {
            document.write("<p>The number " + luckyNumber + " is lucky for you!</p>");
        }

        
        </script> </div>
    </div>
    <footer>
        <p>JavaScript &amp; jQuery: The Missing Manual, 3rd Edition, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
    </footer>
</div>
</body>
</html>

This is a simple Java Script program which allows to enter a number from the user using prompt() command and store that number in a variable called luckyNumber. As far as I know the prompt() function always returns a string version of whatever we type. For example , if I type 7 , the function should return ‘7’. Now since luckyNumber is storing a string, if (luckyNumber == 7 ) should always be false, and always should execute the else part only, because A String value and and a number can not be the same, even if we consider the string as ASCII number. But the code works fine. How? also in my book it’s written that ‘2’==2 is a true condition. How is that even possible?

How to use token authorization with axios in react.js

I have this function in react.js that should access a django rest framework using a token access:

 getAll(token) {
        axios.defaults.headers.common['Authorization'] = "Token " + token
        return axios.get('http://localhost:8000/api/todos/');

I keep getting:

GET http://localhost:8000/api/todos/ 401 (Unauthorized)

I have tried calling the http request on Insomnia and everything seems fine.

How would I implement this token request using axios in react.js

Vue 3 load component dynamically from string

Trying to dynamic load components based on a string.

Should look something like this:

<component v-for="component in components" :in="eval(component)" />

But unfortunately this doesn’t work.

The workaround I’m using for now is creating a function returning the component:

<script setup>
import BarChart from '@/components/BarChart.vue'

const components = ['BarChart']

const stringToComponent = component => {
  return eval(component)
}
</script>

<template>
  <component v-for="component in components" :in="stringToComponent(component)" />
</template>

Why is calling eval directly not working and is it possible to avoid creating a function?

InsertBefore firstChild on event handler using React and Js

I have a working prototype where I cant seem to figure out when I click on a particular button in my nav, then pass that particular index to another component. It doesn’t update the index when I query using “document.querySelector”. My goal is to just move the content to the front childposition/firstChild depending on what button you clicked. So if clicked the first button then last, my last content would be first and so and so on…I’ve tried a timeout and still no luck.

JS:

.....

const Context = createContext(false);

const dataArr = [
  {
    id: "113062",
    name: "Blue",
    region: "US",
    sort: "1"
  },
  {
    id: "115102",
    name: "Red",
    region: "DE",
    sort: "2"
  },
  {
    id: "70884",
    name: "Green",
    region: "US",
    sort: "3"
  },
  {
    id: "114683",
    name: "Yellow",
    region: "US",
    sort: "4"
  },
  {
    id: "112878",
    name: "Pale",
    region: "US",
    sort: "5"
  },
  {
    id: "114682",
    name: "Orange",
    region: "US",
    sort: "6"
  },
  {
    id: "120093",
    name: "Black",
    region: "CH",
    sort: "8"
  },
  {
    id: "120594",
    name: "White",
    region: "CH",
    sort: "9"
  }
];

const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex",
    "& > *": {
      margin: theme.spacing(1)
    }
  },
  grey: {
    border: "4px solid white"
  },
  orange: {
    color: theme.palette.getContrastText(deepOrange[500]),
    backgroundColor: deepOrange[500],
    border: "4px solid black"
  },
  info: {
    margin: "10px"
  },
  wrapper: {
    display: "flex"
  },
  contentWrapper: {
    display: "flex",
    flexDirection: "column"
  },
  elWrapper: {
    opacity: 0,
    "&.active": {
      opacity: 1
    }
  }
}));

const ToggleItem = ({ id, description }) => {
  const { handleChange, selected, classes } = useContext(Context);
  const isSelected = selected.includes(description);

  const handleClick = (idx) => {
    console.log("idx====", idx);
    handleChange(description, idx);
  };

  return (
    <>
      <Avatar
        className={isSelected ? classes.orange : classes.grey}
        onClick={() => handleClick(id)}
      >
        <span style={{ fontSize: ".75rem" }}>{description}</span>
      </Avatar>
    </>
  );
};

const ToggleContainer = ({ selected, list }) => {
  const isSelected = list.filter((element) => selected.includes(element));
  return (
    <>
      {dataArr.map((item, idx) => (
        <div
          key={idx}
          className="carouselWrapper"
          style={{ display: isSelected.includes(item.name) ? "block" : "none" }}
        >
          {item.name}
        </div>
      ))}
    </>
  );
};

const ToggleWrapper = () => {
  const data = [];
  dataArr.map((el) => data.push(el.name));
  const classes = useStyles();
  const [selected, setSelected] = useState([]);
  const [viewAll, setViewAll] = useState(true);

  const handleChange = (val, idx) => {
    setViewAll(false);
    setSelected((selected) => {
      if (selected.length === 1 && selected.includes(val)) {
        return handleViewAll();
      }
      if (selected.includes(val)) {
        return selected.filter((v) => v !== val);
      } else {
        return [val, ...selected];
      }
    });

    setTimeout(() => {
      const someParentObject = document.getElementById("contentWrapper");
      const someChildObject = document.querySelectorAll(".carouselWrapper")[
        idx
      ];

      // eslint-disable-next-line no-unused-expressions
      selected.length > 0 &&
        someParentObject.insertBefore(
          someChildObject,
          someParentObject.firstChild
        );

      console.log(
        "someParentObject.children[0]==",
        someParentObject.firstChild
      );
      console.log("someChildObject", someChildObject);
    }, 2000);
  };

  const handleViewAll = () => {
    setViewAll(true);
    setSelected([]);
  };

  return (
    <Context.Provider
      value={{
        viewAll,
        handleChange,
        handleViewAll,
        selected,
        classes
      }}
    >
      <div className={classes.wrapper}>
        <Avatar
          className={viewAll ? classes.orange : null}
          onClick={handleViewAll}
        >
          <span style={{ fontSize: "0.75rem", textAlign: "center" }}>
            View All
          </span>
        </Avatar>
        {dataArr.map((d, id) => {
          return (
            <div key={id}>
              <ToggleItem id={id} description={d.name} />
            </div>
          );
        })}
      </div>
      <div id="contentWrapper" className={classes.contentWrapper}>
        <ToggleContainer selected={viewAll ? data : selected} list={data} />
      </div>
    </Context.Provider>
  );
};

export default function App() {
  return <ToggleWrapper />;
}

Codesanbox:
https://codesandbox.io/s/update-child-state-from-parent-with-context-hide-class-forked-6x9mtu?file=/src/App.js:0-4499

Backend only works in localhost React + Springboot + docker

I’m trying to deploy a React + Spring Boot App.

3 docker containers with compose (client+server+database) and everything works on localhost. I can access the frontend, login/register, and use the web service as expected.

client: localhost:3333
server: localhost:8080

Once i try deploy it on another machine (desktop w/ ubuntu server), im able to acess the frontend / backend on:

192.168.1.x:3333
192.168.1.x:8080

Also can use postman to POST a new user to 192.168.1.x:8080/api/account/register.

Problem:

I can“t Login / Register using the frontend to make the request.

Devtools Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/account/login. (Reason: CORS request did not succeed). Status code: (null).

Devtools Chrome:

Failed to load resource: net::ERR_CONNECTION_REFUSED localhost:8080/api/account/login:1          
TypeError: Failed to fetch

Login.js

...
        fetch(URL + '/api/account/login', {
            method: 'POST',
            mode: 'cors',
            body: JSON.stringify(data),
            headers: new Headers({
                'Content-Type': 'application/json',
                "Cache-Control": "no-cache",
            })
        }
...

Constants.js

...
       export const URL = 'http://localhost:8080';
...

Being able to POST the user to 192.168.1.x:8080I thought it was the React still trying to POST to localhost, I’ve replaced the URL with export const URL = 'http://192.168.1.x:8080'; but no luck, analyzing both dev tools it shows the request is still going into http://localhost:8080/api/account/login.

It might be something in docker too, I’ve just started using it, don’t know, I’m a bit lost.

Array.join(”) is not working as it should inside of my recursive function

I am attempting to use a recursive approach in order to write a function that will take in a binary string, break it apart into 8 bit sections, and return the string translated to ASCII. As far as I can tell from running debugger, my function should be working. The only problem I’m running into is that when I call join(”) on my ‘currentArray’ variable, it is not in fact joining the array. Any input would be helpful into what I am doing wrong here.

`function binaryToString(binaryBlob, finalString = []) {
  if (binaryBlob.length === 0) return finalString.join('');

  let currentArray = [];
  let binaryArray = binaryBlob.split('');

  currentBit = binaryArray.splice(0, 8);

  currentArray.push(currentBit);
    
  let joinedString = currentArray.join('');
  let base10String = Number(joinedString);
  let ASCII = String.fromCharCode(base10String);
  finalString.push(ASCII);

  return binaryToString(binaryArray.join(''), currentArray, finalString);
};`

Expected outputs:

console.log(binaryToString('010000010100001001000011')); // should return 'ABC'
console.log(binaryToString('001101100011011100111000')); // should return '678'

Opening Link with custom rules using Javascript

I am trying to exclude someone of domain to open in same tab/window (Eg, alias domain, hostname, etc) with a href and rest of them in new tab.

$(document).ready(function() {

   $("a[href^=http]").each(function(){

      // NEW - excluded domains list
      var excludes = [
         'example.com',
         'www.example.com',
         '*.example.com'
      ];
      for(i=0; i<excludes.length; i++) {
         if(this.href.indexOf(excludes[i]) != -1) {
            return true; // continue each() with next link
         }
      }

      if(this.href.indexOf(location.hostname) == -1) {

           // attach a do-nothing event handler to ensure we can 'trigger' a click on this link
           $(this).click(function() { return true; }); 

           $(this).attr({
               target: "_blank",
               rel: "noreferrer nofollow noopener",
               title: "Opens in a new window"
           });

           $(this).click(); // trigger it
      }
   })
}); 

But all the link opening in same tab/window.

I want to create a jQuery loop out of this function instead of copying this function over and over for 12 times

I need some help with creating a loop in this jQuery function. I have some elements on my HTML page with the attribute [level-data="l1"], and I use them in my function to make some changes on the page. I have 12 different attributes starting with the [level-data="l1"] and finishing with the [level-data="l12"]. What I want is to create a jQuery loop instead of copying this function over and over for 12 times, each element will have a different [level-data='ln'] attribute, where n is a number from 1 to 12.
Here is my code:

$('.chart-level[level-data="l1"]').on("click", function () {
        
        $('.chart-level').removeClass('active');
        $('.chart-levels-items .level-info').removeClass('active');
        $(this).addClass('active');
        
        $('.chart-levels-items .level-info[level-data="l1"]').addClass('active'); 
        
        $('.chart-slider-item.page_slider').removeClass('shown');
        $('.chart-slider-item.page_slider[level-data="l1"]').addClass('shown');
        
        $('.chart-slider-item.popup_slider').removeClass('shown');
        $('.chart-slider-item.popup_slider[level-data="l1"]').addClass('shown');
        
        if(window.matchMedia('(max-width: 768px)').matches){
            $([document.documentElement, document.body]).animate({
        scrollTop: $(".chart-levels-items .level-info[level-data='l1']").offset().top
    }, 2000);
        }
    });

Thank you in advance!

how i get querySelectorAll html elements in react?

I am using react with functional component. I also use react-bootstrap , I attached the react-bootstrap carousel , everything is fine with react-bootstrap, for some functionality, I want to get three divs in react , divs has same classes. I know if I use simple html css js then I easily do that,

querySelectorAll(".indicator-btn")

but i want this on react. How can I do that? please suggest me a best practices for that.

This is a my component , in the last i have three divs which i want for Dom.

import React, { useState } from "react";
import Cardcarousel from "./Cardcarousel";
import { Carousel } from "react-bootstrap";
import Brand1img from "../images/brand1.png";
import Airbnbimg from "../images/Airbnb.png";
import Microsoft from "../images/microsoft.png";
import { Row, Col } from "react-bootstrap";

function Carouselx() {
  const [index, setIndex] = useState(0);

  const handleSelect = (selectedIndex, e) => {
    console.log(selectedIndex, "e=>", e);
    setIndex(selectedIndex);
  };

  const isSlide = (slide) => {
    console.log("slide no => " + slide);
    console.log(this);
  };

  return (
    <>
      <div className="px-5 py-3">
        <Carousel activeIndex={index} onSelect={handleSelect} onSlide={isSlide}>
          <Carousel.Item>
            <Row>
              <Col>
                <Cardcarousel
                  name="Technology UI/UX"
                  companylogo={Brand1img}
                  type="Full time job"
                />
              </Col>
              <Col>
                <Cardcarousel
                  name="Technology Backend developer"
                  companylogo={Airbnbimg}
                  type="Part time job"
                />
              </Col>
              <Col>
                <Cardcarousel
                  name="Technology Backend developer"
                  companylogo={Microsoft}
                  type="Internee"
                />
              </Col>
            </Row>
          </Carousel.Item>
          <Carousel.Item>
            <Row>
              <Col>
                <Cardcarousel
                  name="Technology UI/UX"
                  companylogo={Brand1img}
                  type="Full time job"
                />
              </Col>
              <Col>
                <Cardcarousel
                  name="Technology Backend developer"
                  companylogo={Airbnbimg}
                  type="Part time job"
                />
              </Col>
              <Col>
                <Cardcarousel
                  name="Technology front end developer"
                  companylogo={Microsoft}
                  type="Internee"
                />
              </Col>
            </Row>
          </Carousel.Item>
        </Carousel>
        <div className="carusel-indecator-container">
          <div className="indicator-btn indicator-btn1"></div>
          <div className="indicator-btn indicator-btn2"></div>
          <div className="indicator-btn indicator-btn3"></div>
        </div>
      </div>
    </>
  );
}

export default Carouselx;

Open all external URL in new tab

My website have tons of internal and external URL.

for my hostname or "#" href it should open in same tab but for any other domain then my hostname should be open in new tab.

This code making all url open in new tab including internal links.

<base target="_blank" rel="noopener noreferrer">

Please provide the solution in HTML, javascript or PHP.

Discord Bot Cannot Find Module ‘./Commands/balance.js’

—command_handler.js—

const fs = require('fs');

module.exports = (client, Discord) =>{

const command_files = fs.readdirSync('./Commands/').filter(file => file.endsWith('.js'))

for(const file of command_files){

    const command = require(`./Commands/${file}`);

    if(command.name){

        client.commands.set(command.name, command);

    } else {

        continue;
        }
    }
}

—balance.js—

module.exports = {
    name: 'balance',
    aliases: ["bal", "bl"],
    permissions: [],
    description: "Check the user balance",
    async execute(message, args, cmd, client, discord, profileData){
    message.channel.send(`Your wwallet balance is ${profileData.coins}, your monke balance is ${profileData.monke}`);
    }
}

My error message is

Error: Cannot find module ‘./Commands/balance.js’

I don’t no why this is happening. Please help

When pressing a button go to the top of the web page

When I press a button a pop-up window opens.

But at the same time when pressing it we go to the top of the web page. How can I change the code so when we click the button we won’t go to the top of the page?

Thanks a lot!


const modal = document.getElementById("modal")
const overlay = document.getElementById("overlay")
const openBtn = document.getElementById("openBtn")
const closeBtn = document.getElementById("closeBtn")

openBtn.addEventListener("click", function() {
    modal.style.display = "block"
    overlay.style.display = "block"
})

closeBtn.addEventListener("click", function() {
    modal.style.display = "none"
    overlay.style.display = "none"
})