Select an element having conditional render, on the beginning of the code in react.js

I’ve made 2 popup div in react. On the first page load, first popup is visible but i’ve set the opacity of second popup to 0. I’m handling this with a class ‘hide’. And i’m placing this hide class on the second popup based on a state. What i’m trying to achieve here is that i want to select a button having a class of ‘evil-btn’ that is present on the second popup. And add some event listeners to that button. But i’m not able to select that button, as a global variable. It’s returning null. So can anyone suggest me a way how i can select this button in the global scope..?? Below is the code for my Popup component.

import React, { useEffect, useRef, useState } from "react"

function Popup() {
  const [isSecondActive, setIsSecondActive] = useState(false)
  const [firstBtn, setFirstBtn] = useState(true)
  const [secondBtn, setSecondBtn] = useState(false)
  const container2_ref = useRef(null)
  console.log(container2_ref)

  const OFFSET = 100

  const handleMouseOver = (e) => {
    console.log(e.target.innerText)
    if (e.target.innerText === "NO") {
      setFirstBtn(!firstBtn)
      setSecondBtn(!secondBtn)
    }
  }

  const handleClick = (e) => {
    console.log(e.target.innerText)
    if (e.target.innerText === "YES") {
      alert("I Knew You Were Dumb!!")
    }
  }

  const handleSecondClick = (e) => {
    console.log(e.target.dataset.name)
    if (e.target.innerText === "YES") {
      alert("I Knew You Were Dumb!!")
    }

    if (e.target.innerText === "NO") {
      alert(
        "I hate you, you clicked me so hard, I'm going and closing this window"
      )
      // window.close()
    }
  }

  var evilBtn = document.querySelector(".evil-btn")

  document.addEventListener("mouseover", (e) => {
    const x = e.pageX
    const y = e.pageY
    const buttonBox = evilBtn.getBoundingClientRect()
    // console.log("x", x)
    // console.log("y", y)
    let horizontalDistanceFrom = distanceFromBtn(
      buttonBox.x,
      x,
      buttonBox.width
    )
    let verticalDistanceFrom = distanceFromBtn(buttonBox.y, y, buttonBox.height)

    const verticalOffset = buttonBox.height + OFFSET / 2
    const horizontalOffset = buttonBox.width + OFFSET / 2

    if (
      Math.abs(
        horizontalDistanceFrom <= horizontalOffset &&
          Math.abs(verticalDistanceFrom <= verticalOffset)
      )
    ) {
      setButtonPosition(
        buttonBox.x + (horizontalOffset / horizontalDistanceFrom / 2) * 10,
        buttonBox.y + (verticalOffset / verticalDistanceFrom / 2) * 10
      )
    }
  })

  const setButtonPosition = (left, top) => {
    console.log(evilBtn)
    evilBtn.style.left = `${left}px`
    evilBtn.style.top = `${top}px`
  }

  const distanceFromBtn = (buttonPosition, mousePosition, buttonSize) => {
    return buttonPosition - mousePosition + buttonSize / 2
  }

  return (
    <div className='container'>
      <div className='popup'>
        <section className='section-top'>
          {/* CONTAINER 2 START */}
          {
            <div
              ref={container2_ref}
              className={`container second-container container-2 ${
                isSecondActive ? "" : "hide"
              }`}
            >
              <div className='popup'>
                <section className='section-top'>
                  <button
                    onClick={() => setIsSecondActive(false)}
                    className='close-btn'
                  >
                    X
                  </button>
                </section>
                <section className='section-middle'>
                  <h2 className='heading-msg'>
                    Do you really want to quit? But first tell me are you
                    dumb..??
                  </h2>
                </section>
                <div className='btn-containers'>
                  <button
                    data-name='second-yes'
                    onClick={handleSecondClick}
                    className='btn yes-2'
                  >
                    YES
                  </button>
                  <button
                    data-name='second-no'
                    onClick={handleSecondClick}
                    className='btn no-2 evil-btn'
                  >
                    NO
                  </button>
                </div>
              </div>
            </div>
          }
          {/* CONTAINER 2 END */}
          <button onClick={() => setIsSecondActive(true)} className='close-btn'>
            X
          </button>
        </section>
        <section className='section-middle'>
          <h2 className='heading-msg'>Are You Dumb..??</h2>
        </section>
        <div className='btn-container'>
          <button
            onClick={handleClick}
            onMouseOver={handleMouseOver}
            data-name='first-yes'
            className='btn yes-1'
          >
            {firstBtn ? "YES" : "NO"}
          </button>
          <button
            onClick={handleClick}
            onMouseOver={handleMouseOver}
            data-name='first-no'
            className='btn no firstNo'
          >
            {secondBtn ? "YES" : "NO"}
          </button>
        </div>
      </div>
    </div>
  )
}

export default Popup

Javascript module in nuxt [duplicate]

i am learning how to build a js module and upload to npm and install back into nuxt and try to use the function inside. trying to understand the proccess to build a module. but i keep getting error, i try to simple the module much as possible can anyone tell me what i miss out ?

module – dayuntilxmas
github enter link description here

dayuntilxmas

  • README.md
  • index.js
  • package.json

index.js

export function greetPerson(name) {
    return `Hello ${name}`;
}

nuxt/pages/index.vue

<template>
    <div>
        <h1>this is plugins test framework</h1>
    </div>
</template>

<script>
    import {
        greetPerson
    } from 'dayuntilxmas'

    export default {
        data() {
            const greet = greetPerson()
            return {
                greet
            }
        },
        mounted() {
            console.log(this.greet('jade'))
        }
    }
</script>

so what do i missout ? i see some said need to include a html file inside module, but isit needed for some reason ?

the error it return was “Unexpected token ‘export'”

How to get the first day of the next month in JavaScript

I need to get the first day of the next Month for a datePicker in dd/mm/yyyy format.

how can i do it?

i have this code :

var now = new Date();
if (now.getMonth() == 11) {
  var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
  var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

console.log(current)

but it’s give this :

Sat Jan 01 2022 00:00:00 GMT+0200 

i need it like this 01/01/2022

any help here =)?

Why well-know symbols are in Symbol and not in Reflect API

I don’t understand one thing about well-known symbols in Javascript. What is the reason of putting those well-known symbols into Symbol instead of Reflect API? For me seems that the right place for them is the Reflect API as the Reflect API is made for metaprogramming, particularly for reflection and particularly for introspection and self-modification? Does anyone knows the reason of doing so?

Toogle active class using getElementById

I am trying to change class from none to active using document.getElementById but it is just adding active not removing it.

page.html

function toggleIt() {
  let collapseModel = document.getElementById(`collap_id`).className += "content active";
  collapseModel[0].classList.toggle("active")
}
.content {
  padding: 10px 20px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}

.content.active {
  padding: 10px 20px;
  display: block;
  overflow: hidden;
  background-color: #f1f1f1;
}
<button onclick="toggleIt();">Open</button>

<div class="content" id="collap_id">
  Here will be all the details
</div>

When I click on toggle it then it is opening but not closing , it is also showing "Uncaught TypeError: Cannot read properties of undefined (reading 'toggle')"

I have tried many times but it is not toggling.

Change elements display order after click event – javascript

After i click on Calculate button “Reset” button appears below it, but i want to change the display styles how they both appear after the click event. I want them side by side and not on top of each other (picture in link represents the idea) I tried doing it by toggling a class after click, but in that way i could change only one element appearance. What would be the best way to do it?
Button order example

HTML code

<div class="container">
        <header>
          <div class="h1-background">
            <h1 class="h1">Tip calculator</h1>
          </div>
        </header>
        <div class="text">
    
          <p>How much was your bill?</p>
          <form name="theForm3">
            <input class="input-bill" placeholder="Bill Amount $">
            <p>How big tip will you give?</p>
            <!-- DROP DOWN-->
            <div class="select">
              <select class="percents">
                <option value="1">Nothing</option>
                <option value="0.5">5%</option>
                <option value="0.10">10%</option>
                <option value="0.15">15%</option>
                <option value="0.20">20%</option>
                <option value="0.30">30%</option>
    
              </select>
            </div>
          </form>
          <!-- AFTER DROP DOWN-->
          <p>How many people are sharing the bill?</p>
          <input class="input-people" placeholder="Number of people">
          <button onclick="calculateTip(), changeStyle()" class=" button center button-calc"
            type="button">Calculate
          </button>
    
          <button onclick="" class=" button center reset-button" type="button">Reset
          </button>

JS CODE

"use strict";
const buttonCalc = document.querySelector(".button-calc");
function calculateTip() {
    //Selectors
    const inputBill = document.querySelector(".input-bill").value;
    let inputPeople = document.querySelector(".input-people").value;
    const percents = document.querySelector(".percents").value;
    //Event listeners

    //validate input
    if (inputBill === "" || percents == 0) {
        alert("Please enter values");
        return;
    }



    //Check to see if this input is empty or less than or equal to 1
    if (inputPeople === "" || inputPeople <= 1) {
        inputPeople = 1;

        document.querySelector(".each").style.display = "none";

    } else {
        document.querySelector(".each").style.display = "block";
    }


    //Functions
    let total = (inputBill * percents) / inputPeople;
    console.log(total);
    //round to two decimal places
    total = Math.round(total * 100) / 100;
    //next line allows us to always have two digits after decimal point
    total = total.toFixed(2);
    //Display the tip

    // Display alert i there is no TIP
    if (percents == 1) {
        alert(`There is no tip, you must pay only the bill $${total}`)
        return;
    }


    document.querySelector(".reset-button").style.display = "block";
    document.querySelector(".totalTip").style.display = "block";
    document.querySelector(".tip").innerHTML = total;

}


function changeStyle() {
    let container = document.querySelector(".container");
    container.style.height = "400px";
    event.preventDefault();
}


//Hide the tip amount on load
document.querySelector(".reset-button").style.display = "none";
document.querySelector(".totalTip").style.display = "none";
document.querySelector(".each").style.display = "none";

What is difference between these Three?

class AppError extends Error{
    constructor(message,statusCode){
        super(message)
        this.statusCode = statusCode
    }
}

AND

class AppError extends Error{
    constructor(message,statusCode){
        super(message)
        this.message=message
        this.statusCode = statusCode
    }
}

AND

class AppError{
    constructor(message,statusCode){
        this.message = message
        this.statusCode = statusCode
    }
}

I am woking on nodeJs project using mongo.During error handling I created this class but not understading difference between these.

save as json format from Web Speech API Transcript

I am using web speech recognition API in Chrome to get transcripts & store in a string array variable(called notes). I would like to save the full transcripts as json so I can easily use it later.

Currently my project has html, css & script.js, the transcripts are stored in localStorage. May I know how should I work to save the transcript as json? Or if there are any useful links?

I watched the related videos(
https://youtu.be/T7s3st6xfpA?t=205
), result.js will be created if i assign the info in a variable (notesInfo) & call

node saveFile.js

saveFile.js

  const notesInfo = {
      date:'1.12.2021', content:'How are you'
  }

  const fs = require('fs');

  const saveData = (notesInfo) => {
        const finished = (error) => {
            if(error){
              console.error(error)
              return;
            }
        }

        const jsonData = JSON.stringify(notesInfo)
        fs.writeFile('result.json', jsonData, finished)
  }

  saveData(notesInfo)

result.json

{"date":"1.12.2021","content":"How are you"}

But this is suitable for assigning a predictable data ({“date”:”1.12.2021″,”content”:”How are you”})into a variable (notesInfo). But I want my string array variable (notes) which generated from Web Speech Recognition can be saved in a new json file automatically when i start using speech Recognition in my web brower. I worked for days but still have no ideas.

Thank you for your kindness!

Adding screen share option webrtc app. unable to get on other users

i was adding screen share funcanlity to my app but its is not working .. its only show screen share on my side but not on other user.
here is code :-
try{
navigator.mediaDevices.getDisplayMedia({
video: true,
audio:true
}).then(stream => {
const video1 = document.createElement(‘video’);
video1.controls = true;
addVideoStream(video1,stream)

    socket.on('user-connected', userId =>{
        const call = peer.call(userId, stream)
        stream.getVideoTracks()[0].addEventListener('ended', () => {
            video1.remove()
          });
        call.on('close', () => {

        })  
    })
        stream.getVideoTracks()[0].addEventListener('ended', () => {
          video1.remove()
        });
      });
    }catch(err) {
        console.log("Error: " + err);
    }

Text editor in javascript (like notepad)

Hello friends I am learning javascript but I have a question that how can we make a text editor like notepad in javascript by which we can open a text file and edit and save it. With the help of javascript,html and css.

PLEASE ANSWER MY QUESTION

How do I get around SPA framework undoing inserted CSS style?

I have a site and it uses Svelte. I inject custom CSS styling to certain rows of the table, but the styles seems get swapped into totally different rows as soon as the Table get updated with new data.

I tried to debug this issue using Devtools. From what I observe, Svelte reuse tds and change their text contents

The CSS style is injected using Javascript like this,

const tds = tr.getElementsByTagName("td");

tds[1].style.background = "black"

alert box not working properly in JavaScript

<script>
    function fun(){
          let i=document.getElementById("input")
          if(i==="sam")
            {
               alert("welcome SAM")
            }
          else
            {
               alert("welcome user")
            }
        }
      </script>
     
        <input id="input"/>
        <button onclick="fun()">click</click>

if user type input as ‘sam’ it should be follow the if block but every time it execute else part .how to change the condition that when user type ‘sam’ in textbox then only it follow if block or else execute else part

returns doesn’t wait for the cycle to end

I’ve a problem with my code (typescript):

async getAllServers(@Res() response) {
        const servers = await this.serverService.getAllServers();
        let bot = []
        
        servers.map(async server => {
            console.log(server.id)

            bot.push(await this.serverService.getInfo(server.id));

            console.log(bot)
        })
        
        return response.status(HttpStatus.OK).json({
            bot, 
            servers
        })
    }

This function need to return 2 array, but the second array (bot) is always empty.
This is because return is executed before the loop.
How I can execute the return when the loop finish?

Thanks in advance and sorry for bad english.

Removing html tags from API search result in react

The result of search in Wikipedia API in React by the code

const resultsList = results.map((result) => {
    return (
      <div key={result.pageid} className="item">
        <div className="content">
          <div className="header">{result.title}</div>
          {result.snippet}
        </div>
      </div>
    );
  });

which results is search results array, is sth as this image:

enter image description here

What is the best way to remove HTML tags in search result an have sth like this?:

Flower

biological function of a flower is to facilitate reproduction, usually by providing a mechanism for the union of sperm with eggs. Flowers may facilitate outcrossing

Gennifer Flowers

that he had had a sexual encounter with Flowers. During Bill Clinton’s 1992 presidential election campaign, Flowers came forward to say that she had had

Flowers in the Attic

Flowers in the Attic is a 1979 Gothic novel by V. C. Andrews. It is the first book in the Dollanganger Series, and was followed by Petals on the Wind

I am getting an error that says **Nothing was returned from render**. My code is given below

My code is given below and when I render I get a error saying that Nothing was returned from render and asks me to add a return statement but I don’t have any function to add return statement. So I don’t understand where to add a return statement.

    import reportWebVitals from './reportWebVitals';
    
>   ReactDOM.render(
     <React.StrictMode>
       <App />
    </React.StrictMode>,```