Wrapper component executing the inside code even the condition is false

So I have this wrapper component

const AccessControl = ({ content, children }: acProps) => {
  return content ? children : null;
};

And I have used it like this

<AccessControl content={false}>
  {console.log("Ashish")}
  <div>This is executing</div>
</AccessControl>

So it is executing the children even the content is false. If this is how it works, how can I use a wrapper component to avoid ternary operators?

Can JS be isolated within the shadow DOM as it is in an iframe in SO’s code snippets?

The SO site appears to use an iframe to run code snippets. Can any form of web components accept user-provided JavScript and run it in isolation within the shadow DOM only?

I tried both a simple shadow DOM and a custom element example by appending a script tag, and that script can alter the DOM outside the shadow DOM in both instances. Is there a way to isolate the JS?

This almost ten-year-old answer says no but wondered if anything as changed.

Thank you.

“MongoDB Connection Error: MongooseServerSelectionError – connect ENETUNREACH 0.0.7.206:27017”

I’m encountering an issue when trying to connect to my MongoDB server using Mongoose in my Node.js application. The error I’m receiving is as follows:

MongooseServerSelectionError: connect ENETUNREACH 0.0.7.206:27017
at Connection.openUri (C:Personal Projectsservernode_modulesmongooselibconnection.js:825:32)
at C:Personal Projectsservernode_modulesmongooselibindex.js:414:10
at C:Personal Projectsservernode_modulesmongooselibhelperspromiseOrCallback.js:41:5
at new Promise ()
at promiseOrCallback (C:Personal Projectsservernode_modulesmongooselibhelperspromiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:Personal Projectsservernode_modulesmongooselibindex.js:1290:10)
at Mongoose.connect (C:Personal Projectsservernode_modulesmongooselibindex.js:413:20)
at connectDB (file:///C:/Personal%20Projects/server/mongodb/connect.js:6:6)
at startServer (file:///C:/Personal%20Projects/server/index.js:28:5)
at file:///C:/Personal%20Projects/server/index.js:35:1 {
reason: TopologyDescription {
type: ‘Unknown’,
servers: Map(1) { ‘1998:27017’ => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}

My random image is not generating in my react app

If comparison in jQuery with passed in from form values

below is my code for a js file but the if statement is always getting triggered even if quantity =1 and avail =5 . I have checked and avail and quantity do equal the correct numbers. I am also getting avail and quantity from a html form.

var quantity = $("#quantity").val();
var avail = $("#available").val();
if(quantity > avail){
    alert("quanity too large");}

I also tried
if($("#quantity").val() > $("#available").val()){ alert("quantity too large");}
I don’t understand why the if statement is always tigered despite $(“#available”).val() and “#quantity”).val() providing the correct numbers.

Why is my code for compiling Brainfuck not working?

Look at the code below

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width" />
  <title>Brainfuck Coder</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <form name="Brainfucker" oninput="console.log(code)">
    <label for="code">Enter Brainfuck Code:</label>
    <input id="code" name="code"> <br> <br>
    <button id="compBtn"> Compile </button>
  </form>
  <div id="test"></div>
  <img src="img/icon.png">
  <script src="script.js">
    function getInstruction(sourceCode) {
      return sourceCode[0]
    }

    document.getElementById('compBtn').onclick = function() {
      document.getElementById('test').innerHTML = getInstruction(`${code}`)
    }
  </script>
</body>
</html>

When i press the button nothing happens

also for those who see Brainfuck and wonder about it, here: https://en.wikipedia.org/wiki/Brainfuck

I used button instead of input type=”submit” but nothing!

I just gave up

BIM -IOT data integration for construction equipment

IOT integration of construction equipments, I have BIM model of Tower crane and their IOT data in Excel. I want to make a dashboard on AutoDesk platform services where with my BIM model the IoT data will show.
I am a civil engineer so I don’t have knowledge of coding and I have 3 months to do this so please guide me how to do. I saw autodesk tutorial and BIM-IOT integration demo available. I am starting learning coding and also working at the same time. So can you guide me how to start.
I have made my APS account, and now starting making simple viewer till this thing I am fine. After that is I have to do hubs and browser ?. Or I read some answer on stack overflow to make till dashboard section then focus on data visualisation extension. In tutorial they are making dashboard in which in charts or histogram they are showing data of BIM model geometry or material, I don’t want that, I want to show IOT data. So sir please guide me regarding it by step by step what to do and if I will learn javascript then I will definitely able to work on it? Because this project is so important for me.
Dear sir please guide me step by step.

I wnat to make a BIM-IOT integrated dashboard on AutoDesk forge platform.
And one more doubt they are using sensor data with some database, can I use excel.

Hide recaptcha from firebase

I was trying to send sms with firebase. I was trying to hide recaptcha from user experience.

<form>
        <label>Phone Number:</label>
        <input type="text" id="number" class="form-control" placeholder="+91 ********">
         <div id="recaptcha-container"></div>
        <button type="button" class="btn btn-primary mt-3" onclick="sendOTP();">Send OTP</button>
    </form>

<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase.js"></script>

<script type="module">
          
          const firebaseConfig = {
            apiKey: "",
            authDomain: "",
            projectId: "",
            storageBucket: "",
            messagingSenderId: "",
            appId: "",
            measurementId: ""
          };

        firebase.initializeApp(firebaseConfig);
        

        window.onload = function () 
        {  render();  };

        function render() {
          
            window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
                "recaptcha-container",
                {
                  size: "invisible",
                  
                }
              );
               recaptchaVerifier.render();
        }

        function sendOTP() {
            var number = $("#number").val();
           firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function (confirmationResult) {
                window.confirmationResult = confirmationResult;
                coderesult = confirmationResult;
                console.log(coderesult);
                $("#successAuth").text("Message sent");
                $("#successAuth").show();
            }).catch(function (error) {
                $("#error").text(error.message);
                $("#error").show();
            });
        }
        function verify() {
            var code = $("#verification").val();
            coderesult.confirm(code).then(function (result) {
                var user = result.user;
                console.log(user);
                $("#successOtpAuth").text("Auth is successful");
                $("#successOtpAuth").show();
            }).catch(function (error) {
                $("#error").text(error.message);
                $("#error").show();
            });
        }
    </script>

But it shows me following Error:

Uncaught ReferenceError: sendOTP is not defined at
HTMLButtonElement.onclick

Why’s that? What could be the possible solution for above error?

How to fix node-sass error to run React application?

I am trying to use this code as the foundation for a class project, I downloaded it from github: https://github.com/fonov/React-Crypto-Exchange

Whenever I input “yarn install,” it starts to install packages but then I get this error:

Exit code: 1
Command: node scripts/build.js
Arguments:
Directory: C:UserstwiniOneDriveDesktopReact-Crypto-Exchange-masternode_modulesnode-sass
Output:
Building: C:Program Filesnodejsnode.exe C:UserstwiniOneDriveDesktopReact-Crypto-Exchange-masternode_modulesnode-gypbinnode-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
gyp info it worked if it ends with ok
gyp verb cli [
gyp verb cli   'C:\Program Files\nodejs\node.exe',
gyp verb cli   'C:\Users\twini\OneDrive\Desktop\React-Crypto-Exchange-master\node_modules\node-gyp\bin\node-gyp.js',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose',
gyp verb cli   '--libsass_ext=',
gyp verb cli   '--libsass_cflags=',
gyp verb cli   '--libsass_ldflags=',
gyp verb cli   '--libsass_library='
gyp verb cli ]
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "C:UserstwiniAppDataLocalProgramsPythonPython312python.exe" in the PATH
gyp verb `which` succeeded C:UserstwiniAppDataLocalProgramsPythonPython312python.exe C:UserstwiniAppDataLocalProgramsPythonPython312python.exe
gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:UserstwiniAppDataLocalProgramsPythonPython312python.exe -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
gyp ERR! stack SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?  
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (node:child_process:422:12)
gyp ERR! stack     at ChildProcess.emit (node:events:514:28)
gyp ERR! stack     at maybeClose (node:internal/child_process:1105:16)
gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:305:5)
gyp ERR! System Windows_NT 10.0.22621
gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\twini\OneDrive\Desktop\React-Crypto-Exchange-master\node_modules\node-gyp\bin\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:UserstwiniOneDriveDesktopReact-Crypto-Exchange-masternode_modulesnode-sass
gyp ERR! node -v v20.9.0```


I've uninstalled and reinstalled python, and put it in my PATH. I've also deleted the node_modules and tried the install command again. And I've tried updating all of the dependencies in package.json, but no luck. Any suggestions would be appreciated.

How to use Shadow Dom with Javascript and CSS modules

I am trying to use Shadow DOM in my Javascript module and also import a CSS module/sheet into the Javascript module: –

module.js

import sheet from '/styles.css' assert {type: 'css'};

export function message()
{
    const myDiv = document.createElement("div");
    const shadowRoot = myDiv.attachShadow({mode:"open"});
    document.adoptedStyleSheets = [sheet];
    myDiv.textContent = "This is Text";
    return myDiv;
}

As soon as I add the line to .attachShadow() the content of the DIV “This is Text” stopped appearing.

If I went further an tried to adoptStyleSheets to the shadowRoot instead of the document then no CSS from styles.css took effect.

styles.css

host:: {
    background-color: yellow;
}
div {
    background-color: red;
}

What do I have to do to be able to use Shadow DOM in my Modules in concert with Adopted Styles from CSS modules?

test_mod.html

<!DOCTYPE html>
<html>
<style type="text/css">
div div {
    height: 100px;
    width: 100px;
    text-align: center;
    background-color: lightblue;
}
</style>
<script type="module">
import {message} from "http://localhost/message.js";

document.getElementById("demo").appendChild(message());

</script>
<body>
<h1>JavaScript Modules</h1>

<div id="demo"></div>

</body>
</html>

Offcanvas dismiss button does not work when instance initialised via Javascript

I have offcanvas as part of the page layout. It does not show by default, but I want it to always show on large screens. On small screens it should have a button to dismiss it. Another button to show the offcanvas is placed on the menu panel underneath it.

I’m using JavaScript on page load and on page resize to show the offcanvas when if screen is large. If the user then scales the screen down, the offcanvas should remain visible until dismissed.

The issue is that the dismiss button works on the offcanvas only if it has not been initialised via JS. I.e. if opened on a small screen, the offcanvas is not visible and the two bottons can be used to toggle back and forth. But once the offcanvas has been triggerd via JS on a large screen, the dismiss button no longer works when the screen is downsized. I’m struggling to figure out if it has lost an EventListener and how to add it back, if so.

Layout:

<!-- Button to show offcanvas (positioned underneath it) --> 
<div>
    <button class="btn" type="button" id="off-canvas-body-toggle" data-bs-toggle="offcanvas" data-bs-target="#floating-menu">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#422543" class="bi bi-arrow-bar-right" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M6 8a.5.5 0 0 0 .5.5h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 0 0-.708.708L12.293 7.5H6.5A.5.5 0 0 0 6 8Zm-2.5 7a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5Z" />
        </svg>
    </button>
</div>

<!-- Offcanvas -->
<div class="offcanvas offcanvas-start" data-bs-scroll="true" data-bs-backdrop="false" tabindex="-1" id="floating-menu">
    
    <!-- Bootstrap classes d-xl-none d-lg-none hides the div with dismiss button on large screen -->
    <!-- But it becomes visible when the screen is downsized -->
    <div class="offcanvas-header d-xl-none d-lg-none">
        <!-- Dismiss button that does not work corectly -->
        <button type="button" class="btn" id="off-canvas-body-dismiss" data-bs-dismiss="offcanvas">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#422543" class="bi bi-arrow-bar-left" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5ZM10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5Z" /></svg>
        </button>
    </div>

    <div class="offcanvas-body">
    <!-- This contains an accordion and works fine -->
    </div>
</div>

JS:

// Once the HTML has loaded
document.addEventListener("DOMContentLoaded", function () {

// If on large screen, show offcanvas upon page load
adjust_layout();

// On resize - if large screen then always show offcanvas
addEventListener("resize", adjust_layout);
}

function adjust_layout() {
  // Get the Div that contains the offcanvas
  const menu = document.getElementById("floating-menu");
  var bsOffcanvas = new bootstrap.Offcanvas(menu);

  // If large screen - show the offcanvas
  let width = window.innerWidth;
  if (width >= 992) {
    bsOffcanvas.show();
  }
}

Javascript, same function, multiple elements one at a time

I created a carousel slider similar to the one in UIkit slider, I want to use this function to multiple carousel in the same html page but it’s not working as expected because I am using this line of code which query single carousel only:

const carousel = document.querySelector(".c-carousel-inner");

I’ve tried using this but apparently on button press it will trigger the other carousel also

const carousels = document.querySelectorAll(".c-carousel-inner");
carousels.forEach((carousel) => {
// code here
});

I’ve seen some solution which uses constructor, but I’m not sure if that’s the best approach here

Here’s my full javascript code without any applied code from above

const carousel = document.querySelector(".c-carousel-inner");
const carouselLength = carousel.children.length;
const carouselItemWidth = document.querySelector(".c-carousel-inner .c-carousel-item").offsetWidth;
const carouselButtons = document.querySelectorAll(".c-carousel-control");
let startX, scrollSum = 0, mouseIsDown, count = 0, mx, moving=false, lastDirection, prevScroll;

carouselButtons.forEach((button) => {
    button.addEventListener("click", function(){
        if (button.id == "carousel-right") {
            if (prevScroll) {
                mouseToLeft();
            }
            prevScroll = true;
            moveToLeftSnap();

        } else if (button.id == "carousel-left") {
            if (!prevScroll) {
                mouseToRight();
            }
            moveToRightSnap();
            prevScroll = false;
        }
    });
})

function mouseToLeft() {
    if (count >= carouselLength) {
        count = 0;
    }
    count++;
    for (i=0; i < carouselLength; i++) {
        carousel.children[i].style.removeProperty("order");
        if (i < count) {
            carousel.children[i].style.order = "1";
        }
    }
}

function mouseToRight() {
    if (count <= 0) {
        count = carouselLength;
    }
    count--;    
    for (i=carouselLength-1; i>=0; i--) {
        carousel.children[i].style.removeProperty("order");
        if (i >= count) {
            carousel.children[i].style.order = "-1";
        }        
    }
}

function moveToRightSnap(value=carouselItemWidth) {
    carousel.style.removeProperty("transition");
    carousel.style.transform = `translate3d(-${value}px, 0, 0)`;
    setTimeout(() => {
        carousel.style.transition = `transform 0.342s ease`;
        carousel.style.transform = `translate3d(0, 0, 0)`;
    }, 1); 
}

function moveToLeftSnap(value=0) {
    carousel.style.removeProperty("transition");
    carousel.style.transform = `translate3d(${value}, 0, 0)`;
    setTimeout(() => {
        carousel.style.transition = `transform 0.342s ease`;
        carousel.style.transform = `translate3d(-${carouselItemWidth}px, 0, 0)`;
    }, 1);
}

const startDrag = (e) => {
    mouseIsDown = true;
    startX = e.pageX;
    mx = e.pageX;
    carousel.style.removeProperty("transition");
}

const dragging = (e) => {
    if (mouseIsDown) {
        scrollSum = e.pageX - startX;
        console.log(scrollSum);
        if (mx < e.pageX) {
            lastDirection = "right";
        } else if (mx > e.pageX) {
            lastDirection = "left"
        }
        if (scrollSum > 0) {
            startX = e.pageX + carouselItemWidth;
            scrollSum = scrollSum - carouselItemWidth;
            if (!prevScroll) {
                mouseToRight();
            }
        } else if (prevScroll || scrollSum <= -carouselItemWidth) {
            scrollSum = 0;
            startX = e.pageX;
            mouseToLeft();
            prevScroll = false;
        }
        carousel.style.transform = `translate3d(${scrollSum}px,0,0)`;
        mx = e.pageX;
    }
} 

const stopDrag = () => {
    mouseIsDown = false;
    if (lastDirection == "right") {
        moveToRightSnap(scrollSum);
    } else if (lastDirection == "left") {
        moveToLeftSnap(scrollSum);
        prevScroll = true;
    }
}

carousel.addEventListener("mousedown", startDrag);

document.addEventListener("mousemove", dragging);

document.addEventListener("mouseup", stopDrag);

HTML code currently only single carousel is added here to make it short

<div class="main-container">
  <div class="container">
    <div class="c-carousel">
      <ul id="" class="c-carousel-inner d-flex">
        <% topAiring.forEach((item, index) => { %>
        <li class="c-carousel-item item-<%= index + 1 %> col-3 <%= index == 0 ? 'active' : '' %>">
          <img src="<%= item.images.jpg['image_url'] %>" draggable="false" class="d-block w-100" alt="...">
        </li>
        <% }) %>
      </ul>
      <button id="carousel-left" class="c-carousel-control" type="button">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
      <button id="carousel-right" class="c-carousel-control" type="button">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
    </div>
  </div>
</div>

React Quill not rendering

I am trying to create a form using the ShadCN component and display a Cloudinary component or a WYSIG editor depending on the previous select field’s value, but only the loading component is displayed from the RichEditor component.

I am seeing some hydration issues but they seem not to be related.

This is the form component:

<FormField
    control={form.control}
    name="type"
    render={({ field }) => (
        <FormItem>
            <FormLabel>Tipo</FormLabel>
            <Select
                disabled={loading}
                onValueChange={field.onChange}
                value={field.value}
                defaultValue={field.value}
            >
                <FormControl>
                    <SelectTrigger>
                        <SelectValue
                            defaultValue={field.value}
                            placeholder="Selecciona un tipo"
                        />
                    </SelectTrigger>
                </FormControl>
                <SelectContent>
                    <SelectItem
                        key="image"
                        value="Imagen"
                    >
                        Imagen
                    </SelectItem>
                    <SelectItem
                        key="html"
                        value="Texto"
                    >
                        Texto
                    </SelectItem>
                </SelectContent>
            </Select>
        </FormItem>
    )}
/>

<FormField
    control={form.control}
    name="content"
    render={({ field }) => (
        <FormItem>
            <FormLabel>Contenido</FormLabel>
            <FormControl>
                {form.getValues().type === "Imagen" ? (
                    <ImageUpload
                        value={field.value ? [field.value] : []}
                        disabled={loading}
                        onChange={(url) => field.onChange(url)}
                        onRemove={() => field.onChange("")}
                    />
                ) : (
                    <RichEditor
                        value={field.value}
                        disabled={loading}
                        onChange={field.onChange}
                    />
                )}
            </FormControl>
        </FormItem>
    )}
/>

And this is the file rich-editor.tsx:

import dynamic from 'next/dynamic'
import { useEffect, useState } from 'react'

import 'react-quill/dist/quill.snow.css'

const QuillNoSSWrapper = dynamic(import('react-quill'), {
    ssr: false,
    loading: () => <p>Cargando editor ...</p>
})

interface RichEditorProps {
    onChange: React.Dispatch<React.SetStateAction<string>>
    value: string
    disabled: boolean
}

const modules = {
    toolbar: [
        [{ header: '1' }, { header: '2' }, { font: [] }],
        [{ size: [] }],
        ['bold', 'italic', 'underline', 'strike', 'blockquote'],
        [
            { list: 'ordered' },
            { list: 'bullet' },
            { indent: '-1' },
            { indent: '+1' },
        ],
        ['link', 'image', 'video'],
        ['clean'],
    ],
    clipboard: {
        // toggle to add extra line breaks when pasting HTML:
        matchVisual: false,
    },
}

const RichEditor: React.FC<RichEditorProps> = ({
    onChange,
    value,
    disabled
}) => {
    const [isMounted, setIsMounted] = useState(false)

    useEffect(() => {
        setIsMounted(true)
    }, [])

    if (!isMounted) {
        return null
    }

    return (
        <div>
            <QuillNoSSWrapper
                theme="snow"
                value={value}
                onChange={onChange}
                readOnly={disabled}
                modules={modules}
            />
        </div>
    )
}

export default RichEditor

Can you see what’s wrong here?

Why is this react-django app not rendering anything

my App.js is in appname/src/components :

import React, { Component } from "react";
import { render } from "react-dom";

export default class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1>This is the App.js</h1>
      </div>
    );
  }
}

const appDiv = document.getElementById("app");
render(<App />, appDiv);

My index.js in appname/src:

import App from "./components/App";

const appDiv = document.getElementById("app");
ReactDOM.render(<App />, appDiv);


why is the server not rendering anything?

see my templates app name index.html in appname/templates/appname seems to be doing just fine:

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Testing DJREACT with Yarn</title>
    <link rel="stylesheet" href="{% static 'css/style.css' %}" />
  </head>
  <body>
    <div id="main">
      <div id="app"></div>
    </div>
    <script src="{% static 'frontend/main.js' %}"></script>
  </body>
</html>

I think I did the installation correctly. The title of the web is indeed getting rendered but the body is not.

console in the browser is showing this errors:
127.0.0.1/:9

   GET http://127.0.0.1:8000/static/css/style.css net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:15

   GET http://127.0.0.1:8000/static/frontend/main.js net::ERR_ABORTED 404 (Not Found)