App not showing after import new component in App JS

After I import a new component in app.js the app renders nothing on the browser and does not even get an error. The new component is cart.js. Also sharing the modal.js code because it’s used in the cart component as a wrapper.
Also when I remove the Cart component from App JS, the app runs fine.

App JS:

    import Header from "./components/Layout/Header";
    import Meals from "./components/Meals/Meals";
    import Cart from "./components/Cart/Cart";
    
    function App() {
      return (
        <>
          <Cart />
          <Header />
          <main>
            <Meals />
          </main>
        </>
      );
    }
    
    export default App;

Cart.js file:

import Modal from "../UI/Modal";
import classes from "./Cart.module.css";

const Cart = (props) => {
  const cartItems = (
    <ul className={classes["cart-items"]}>
      {[
        {
          id: "c1",
          name: "Biryani",
          Amount: 2,
          price: 250,
        },
      ].map((item) => (
        <li>{item.name}</li>
      ))}
    </ul>
  );

  return (
    <>
      <Modal>
        {cartItems}
        <div className={classes.total}>
          <span>Total Amount</span>
          <span>200</span>
        </div>
        <div className={classes.actions}>
          <button className={classes["button--alt"]}>Close</button>
          <button className={classes.button}>Order</button>
        </div>
      </Modal>
    </>
  );
};

export default Cart; 

Modal.js is used as a portal for the Cart component and ID “overlays” is coming from the index.html used as a portal.

import React from "react";
import ReactDOM from "react-dom";
import classes from "./Modal.module.css";

const Backdrop = (props) => {
  return <div className={classes.backdrop}></div>;
};

const ModalOverlay = (props) => {
  <div className={classes.modal}>
    <div className={classes.content}>{props.children}</div>;
  </div>;
};

const portalEl = document.getElementById("overlays");

const Modal = (props) => {
  return (
    <>
      {ReactDOM.createPortal(<Backdrop />, portalEl)}
      {ReactDOM.createPortal(
        <ModalOverlay>{props.childres}</ModalOverlay>,
        portalEl
      )}
    </>
  );
};

export default Modal;

Only show 3 first characters of months from Input type Month

So I’m using the input type “Month” and is showing fine the month in this format: January 2021, so besides that, I want to achieve something else just to show the first three characters, for example: Jan Feb Oct, is there any attribute or way to do it?

Or lastly a library that offers that (but I want to avoid this)

Mui and emotion css breaking styles on build time next js

I am trying to use MUI and emotion for custom skeleton loaders in my app. I just switched to the emotion based MUI configuration. I followed the guide perfectly but at build time, the styles don’t reflect at all. Here is my code:

/_document.js

import Document, { Html, Head, Main, NextScript } from 'next/document'
import React from 'react';
import { gTagKillSwitch } from './api/dev-switches';
import createEmotionServer from '@emotion/server/create-instance';
import createEmotionCache from '../src/createEmotionCache';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html translate="no" className="notranslate">
        <Head>
  
            rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
          />
        <meta name="msapplication-TileColor" content="#ffffff" />
        <meta name="theme-color" content="#ffffff"/>
        {this.props.emotionStyleTags}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument;

MyDocument.getInitialProps = async (ctx) => {

  const originalRenderPage = ctx.renderPage;

  const cache = createEmotionCache();
  const { extractCriticalToChunks } = createEmotionServer(cache);

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) =>
        function EnhanceApp(props) {
          return <App emotionCache={cache} {...props} />;
        },
    });

  const initialProps = await Document.getInitialProps(ctx);
  const emotionStyles = extractCriticalToChunks(initialProps.html);
  const emotionStyleTags = emotionStyles.styles.map((style) => (
    <style
      data-emotion={`${style.key} ${style.ids.join(' ')}`}
      key={style.key}
      dangerouslySetInnerHTML={{ __html: style.css }}
    />
  ));

  return {
    ...initialProps,
    styles: [
      ...React.Children.toArray(initialProps.styles),
      ...emotionStyleTags,
    ],
  };
};

/_app.js

import PropTypes from 'prop-types';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { CacheProvider } from '@emotion/react';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';



TimeAgo.addLocale(en);

const clientSideEmotionCache = createEmotionCache();

  
  function MyApp (props){

    const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;


  return(
    <CacheProvider value={emotionCache}>
      <Provider store={store}>
        <Head>
          <meta name='viewport' content='initial-scale=1, viewport-fit=cover' />
        </Head>
        <ThemeProvider theme={theme}>
           <CssBaseline /> 
          {returnPage()}
        </ThemeProvider>
      </Provider>
    </CacheProvider>
  );
}

MyApp.propTypes = {
  Component: PropTypes.elementType.isRequired,
  emotionCache: PropTypes.object,
  pageProps: PropTypes.object.isRequired,
};


const makeStore = () => store;
const wrapper = createWrapper(makeStore)


export default wrapper.withRedux(MyApp);

/createEmotionCache.js

import createCache from '@emotion/cache';

export default function createEmotionCache() {
  return createCache({ key: 'css', prepend: true });
}

The styles work perfectly fine in the dev-server but it doesn’t work well at build time. How do I solve this issue?

The setup for the styles is exactly as same as mentioned in the documentation for nextjs applications

Please do help me out!!

Thanks,
S Aadhit

JQuery slideToggle works on local, but not live site

I have a few different jQuery slideToggles on my site and I have no issue but the mobile navigation menu I can’t seem to work. I have it working fine on my local site but on my live site nothing happens.

My live site is https://toolcurve.com

<ul class="menu">
    <li class="item"><a href="">Main menu link</a>
        <img src="drop-chev.svg" class="sub-menu-drop ">
        <ul class="dropdown">
            <li class="sub-item"><a href=""></a>Sub Menu Link</li>
            <li class="sub-item"><a href=""></a>Sub Menu Link</li>
        </ul>
    </li>
    <li class="item"><a href="">Main menu link</a>
    <img src="drop-chev.svg" class="sub-menu-drop ">
        <ul class="dropdown">
            <li class="sub-item"><a href=""></a>Sub Menu Link</li>
            <li class="sub-item"><a href=""></a>Sub Menu Link</li>
        </ul>
    </li>
</ul>

The JS I use is

$(function(){
        if (window.innerWidth < 768){
        var $submenu = $(".dropdown");
        $(".sub-menu-drop").on("click", function(e){
            $(this).next($submenu).slideToggle();
        });
        }
    });

This is very similar to the other slideToggles i have on my site which all work fine but I just seem to get this one to work on my live site, but it does work fine on my local site.

Html not loading properly, nuxt 3 onMounted

I am having trouble with an implementation of Nuxt 3 and Threejs.

<template>
  <div>
    <canvas ref="webgl" class="canvas"></canvas>
  </div>
</template>

<script setup>
import * as THREE from "three";

import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
const webgl = ref(null);

var renderer;
onMounted(async () => {
  await nextTick();
  console.log();
  if (process.client) {
    const canvas = document.querySelector(".canvas");
    //const canvas = webgl.value; Silent error but does not work
    console.log(canvas);
    //Getting canvas element

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(32, 1, 0.1, 1000).translateZ(15);

    renderer = new THREE.WebGLRenderer({
      canvas,
      alpha: true,
      antialias: true,
    });

    // Creating a renderer
    renderer.setClearColor(0x000000, 0);
    renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
    renderer.setPixelRatio(window.devicePixelRatio);

    // Avoid pixelation on resize
    window.onresize = () => {
      renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
    };

    // Creating loader for custom GLTF models
    const loader = new GLTFLoader();
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("https://www.gstatic.com/draco/v1/decoders/");
    loader.setDRACOLoader(dracoLoader);

    const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 0.9);
    hemiLight.position.set(0, 0, 15);
    scene.add(hemiLight);

    let model;
    loader.load(
      // resource URL
      "/models/molecule.glb",
      // called when the resource is loaded
      function (gltf) {
        model = gltf.scene;
        model.position.set(0, -0.4, -1);
        if (model) model.rotation.x += 90;
        scene.add(model);
      },
      // called while loading is progressing
      function (xhr) {
        console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
      },
      // called when loading has errors
      function (error) {
        console.log("An error happened", error);
      }
    );
    let x = 0;

    // start the loop
    renderer.setAnimationLoop(() => {
      if (model) {
        // --- Simple Rotation Animation
        // model.rotation.y += 0.002;
        // if (model.rotation.y >= 360) model.rotation.y = 0;
        // if (model.rotation.z >= 0) model.rotation.z -= 0.002;
        // else if (model.rotation.z <= 0) model.rotation.z += 0.002;
        // else {
        //   model.rotation.z += 0.0002;
        // }
        // --- Floating Animation
        x = x + 2;
        model.position.y = Math.cos(x * 0.01) * 0.3;
        model.rotation.z = Math.sin(x * 0.01) * 0.2;
        model.rotation.x = Math.sin(x * 3.14 * 0.01) * 0.02 + 90;
      }
      renderer.render(scene, camera);
    });
  }
});

onUnmounted(() => {
  renderer.setAnimationLoop(null);
});
</script>

<style scoped>
.canvas {
  width: 100%;
  height: 100%;
  z-index: 1;
}
</style>

I use this code to load a 3d model inside a vue component, which wraps an html canvas. Which then is animated and mounted on the page.

If I load the page normally, then everything works, and the animation with the model is shown. But if I navigate to another page and back (via the Vue/Nuxt router)

I get the following error:
enter image description here

As if the html canvas did not exist at all. Even though I am declaring it after the component is mounted…

I also tried using template refs, but then the model just does not load, and there is no error too.

Oh and for the record, I am running the app on SSR mode.

I will be forever grateful if you can help me.
Thanks in advance!

Not getting nested property value [closed]

I have a function to convert units to my native language. My function –

const toCorrectUnitLanguage = (unit, langLocale = 'en') => {
  const savedUnits = {
    sec: { en: 'Sec', bn: 'সেকেন্ড' },
    min: { en: 'Min', bn: 'মিনিট' },
    hour: { en: 'Hour', bn: 'ঘন্টা' },
  }
  if (savedUnits[unit.toLowerCase()]) {
    return savedUnits[unit.toLowerCase()][langLocale];
  }
  return unit;
}

console.log(toCorrectUnitLanguage('sec'))
console.log(toCorrectUnitLanguage('sec', 'en'))
console.log(toCorrectUnitLanguage('sec', 'bn'))

I am getting the correct object when I am logging savedUnits[unit.toLowerCase()].
I am also getting the value I want if I hard code savedUnits[unit.toLowerCase()]["en"]

But I am getting undefined when I am returning savedUnits[unit.toLowerCase()][langLocale]

Any suggestions? Thanks in advance.

Edit:
Calling the function like this –

toCorrectUnitLanguage('sec',langLocale)

My node version is 13.14.0. Could that be an issue?

Word Process with Javascript [closed]

Change the following words to be a word based on the position of the character replacement with javascript.

Input
A sentence

Output
A word without whitespace

Sample:
input: describe
output: deescrib

input: Create a new account
output: cccreeeaaattnnwou

Dynamic fetch requests in parallel

I would like to know how I can do dynamic fetch requests in parallel, I have been trying to do this for 12 hours and I cant figure it out, I looked everywhere on google and StackOverflow, I really am tired.

let list = await fetch(`${domain}/segment?mode=${mode}&type=${type}`,  {    method: 'POST', body: fd   })
let result = await list.json()

I have the following fetch request that I send, where the body is generated for each request, It’s never the same body, the body gets generated dynamically by the functions. Is there a way to send all the requests at once, then wait for them to return a response, then proceed with the rest of my code?

‘User’ is not recognized as an internal or external command,”durring running npm start”

please help to resole this error, i created new react project ,then i run npm start cmd ,i am getting this error

C:Rachnap-16 working with Form & User Input using http requestuser-input-project>npm start

> [email protected] start
> react-scripts start

'User' is not recognized as an internal or external command,
operable program or batch file.
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'C:Rachnareact-scriptsbinreact-scripts.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []

}