React js adding regular script to react component

I am new to posting questions to stackoverflow. I have a question about React js. Trying to add an old html page with a script I made.

When I take off the comment from the import it breaks the app. Any way to fix this?
Leaving the script commented lets the page load with the css but nothing else.

Here is the code in the component

import './style.css';
// import './script.js';
import { NavBar } from "../Nav";


export function CountDownTimer() {
    
    return (
        <>
        <NavBar />

    <h1>Countdown</h1>
    <h2>Default set to new years 2050</h2>

    

    <div className='calendar'>
        <input type='date' id='Date' />
        <button onclick="changeDate()">Countdown</button>
    </div>
    

    <div className='timer-container' >
        <div>
            <div id='days'></div>
            <span>days</span>
        </div>
        <div>
            <div id='hours'></div>
            <span>hours</span>
        </div>
        <div>
            <div id='minutes'></div>
            <span>minutes</span>
        </div>
        <div>
            <div id='seconds'></div>
            <span>seconds</span>
        </div>
    </div>


    <div className='timer-container' >
        <div>
            <div id='thours'></div>
            <span>Total hours</span>
        </div>
        <div>
            <div id='tminutes'></div>
            <span>Total minutes</span>
        </div>
        <div>
            <div id='tseconds'></div>
            <span>Total seconds</span>
        </div>
    </div>

    

    {/* <script src="script.js"></script> */}

    </>
    );
}

and the script.js

//target date to countdown to
var setDate = new Date('2050-01-01T00:00:00');
console.log('Date set to: ' + setDate);




var currentDate;
function countdown() {
    currentDate = new Date();


    var time = (setDate.getTime() - currentDate.getTime());
    var seconds = Math.floor(time/1000)%60;
    var minutes = Math.floor(time/60/1000 % 60);
    var hours = Math.floor(time/1000/3600 % 24);
    var days = Math.floor(time/3600/24/1000);

    

    // console.log('days, hours, minutes, seconds', days, hours, minutes, seconds);
    document.getElementById("days").innerHTML = days;
    document.getElementById("hours").innerHTML = hours;
    document.getElementById("minutes").innerHTML = minutes;
    document.getElementById("seconds").innerHTML = seconds;

    var totalSeconds = Math.floor(time/1000);
    var totalMinutes = Math.floor(time/60/1000);
    var totalHours = Math.floor(time/1000/3600);

    document.getElementById("tseconds").innerHTML = totalSeconds;
    document.getElementById("tminutes").innerHTML = totalMinutes;
    document.getElementById("thours").innerHTML = totalHours;
}

function changeDate() {
    var newDate = document.getElementById("Date").value;
    console.log("newDate: ", newDate);
    setDate = new Date(newDate+"T00:00:00");
}

countdown();



setInterval(countdown, 1000);


How can I set src and alt attibutes on an image tag using Javascript

Javascript is something that I am learning bit by bit, so please excuse my ignorance…! 😉

I have a list of images in a gallery, and I am creating a modal on a click event. I have managed to collect all of the sources for the images into an array and have then used the forEach method to appended an li and img tag into a parent ul, with all of the sources going into the src attribute.

My problem is I also have an array of alt attributes as well that I also need to set into the same list of images.

I don’t think I can do both attibutes in one forEach loop, and it seems too messy to do a second loop for the alt attributes. There must be a simpler way, it’s just beyond my current undersatnding.

Here is the code I already have below, I was wondering if perhaps I should be looking at a Json object instead rather than this approach?

 $('.gallery-image img').click(function(){
            $('.modal').addClass('show');
            var images = document.getElementsByClassName('aurora-gallery-image');
            var imageSources = [];
            var imageTitles = [];
            for (var i = 0; i < images.length; i++) {
                 imageSources.push(images[i].src);
                 imageTitles.push(images[i].alt);
            }
           imageSources.forEach(imageFunction);
            
            function imageFunction(item){
               $('.image-modal ul').append('<li class="image-modal-item"><img class="modal-content" alt="" src="' + item + '" /><p id="aurora-gallery-image-title">  </p></li>');
            }
           
           
      }); 

reduce array of numbers into object with key and value amount [duplicate]

I have an array of numbers const array = [1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5];

I’m trying to return an object like this {
‘1’: 1,
‘2’: 1,
‘3’: 2,
‘4’: 3,
‘5’: 4
}

This is a code I’m use for now but it did’n calcutale values.
I’ve tried to google but i didn’t find how to solve it.
Please help

const array = [1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5];
const convertArrayToObject = (array) =>
array.reduce((acc, curr) => ({
...acc, [curr] : curr
}), {});

React select onChange is getting triggered for the second time with old value

I am using React Select to show list of items . On change of item , i want to show a warning based on some flag . If flag is true , Dialog box will be displayed and and confirm of that , I want to allow the change . For every on on change , i am storing the selected item in local state use effect . On click of confirm from dialog box or if flag is false , i am dispatching actions to store them in redux store .

I am having issue when Dialog box is appearing and on click of confirm, item in dropdown is changing , but onChange is getting called again with first value ,Hence dropdown is going back to initial value .

Why is onChange getting called twice .

Tried event.preventDefault , but not working.

const [name, setName] = React.useState();

const changeValue = (event,selectedItem) => {
    event.preventDefault()
    setName(selectedItem) // storing in UseState hook 
    if(flag){
        props.toggleWarningDialog(true);
    }
    else {
        props.onChangeItem(selectedItem);
    }
}

const handleConfirmChange = (event) => {
        event.preventDefault()
        props.onChangeItem(name); //getting from useState hook and storing in redux by dispatching an action
 }  

Getting the value of array out of scope of a function [duplicate]

I want to know if there is any way to get the value of ref inside an async function.
the code below show the example for my problem:

var results =ref([])
    projectFirestore.collection('patients').where('ssn', '==', '211').onSnapshot((snap) => {
            snap.docs.forEach((doc) => {
              results.value.push(doc.data());
            })  
            
      })
    console.log(results.value.length);  

the output of the console is 0, but if I move the console function inside the function it will print ’21’ (the length of array that retrieved from DB)

is there a way to do a conditional alternative in js

my code is

if(name === 'banana' || name === 'orange') //do something

the word “name” is in my code twice, is there something that I can do to do not repeat it? if I do

if(name === 'banana' || 'orange')

the computer doesn’t understand, maybe there is another way that i dont know yet,

thanks very much

WebdriverIO based automated tests saved in the network drive doesn’t run

We are keeping my WebDriverIO based automated test scripts in network drive, so that my team mates can also access and run the scripts when needed.

However when we try to run the script from the shared location, it doesn’t trigger and takes a long time without any further information, and eventually we need to abort it.

As you see in the below image, node_modules are also available in the shared folder at the same location.

enter image description here

Please suggest what is the best way to run the test scripts in this kind of set up?

How can I fix this cannot get error in Heroku?

I’m trying to deploy my app to Heroku, it runs fine locally. I’m getting the error in the logs after the build:

heroku[router]: at=info method=GET path="/" host=appname.herokuapp.com  fwd="xx.xxx.xxx.xxx" dyno=web.1 connect=0ms service=8ms status=404 bytes=415 protocol=https

When trying to view the app I get the cannot GET / error, I’ve looked through a bunch of similar errors & can’t find where I’m going wrong.my app.js file is located at ./server/app.js

app.js

const express = require("express");
const http = require("http");
var cors = require("cors");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const path = require("path");
const mongoose = require("mongoose");
const createError = require("http-errors");
const { Router } = require("express");
let codeRoutes = require("./api/code-routes.js");
/**
 * App configurations
 */
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan("dev"));
app.use(cors());
app.use(express.static(path.join(__dirname, "../dist/my-app")));
app.use(
  "/",
  express.static(path.join(__dirname, "../dist/my-app"))
);
/**
 * Variables
 */

const MONGODB_URI =
  "myMongoDBConnString";

/**
 * Database connection
 */
mongoose
  .connect(MONGODB_URI, {
    promiseLibrary: require("bluebird"),
    useUnifiedTopology: true,
    useNewUrlParser: true,
  })
  .then(() => {
    console.debug(`Connection to the database instance was successful`);
  })
  .catch((err) => {
    console.log(`MongoDB Error: ${err.message}`);
  }); // end mongoose connection

app.use("/api", myApi);

app.listen(process.env.PORT || 3000, function () {
  console.log("Application is running at localhost:" + app.get("port"));
});

package.json

{
  "name": "myapp",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node ./server/app.js",
    "server": "nodemon ./server/app.js",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "localhost": "ng build && node ./server/app.js"
  },

Refresh Web Application on Network Connection

I have an angularjs web application that is being hosted on server and displayed on client device using Windows form webbrowsercontrol. The application runs 24/7 in the device. I am also detecting the keep alive of server from client by regularly pinging the server for network connectivity. But there are scenarios when keep alive is true and the webpage goes to “Page Not Found” and stuck there due to intermittent connection loss between server and client.

Is there someway I can refresh the webpage on its own to recover from “Page not found” on server connection?

How do I make a cookie out of the user input from a form?

How do I make a cookie out of the user input from a form like this:

<form>
 <label for="name">Name:</label>
 <input type="text" id="name" name="name">
 <input type="submit" value="Submit">
</form>

or like this:

<form>
  <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
  <label for="vehicle3"> I have a boat</label>
</form>

Is there a way to disable jump links within a page or the div itself?

So, I’ve been trying to create a slider using only CSS and have been trying to avoid JS. Here’s what I’ve got so far:

:root{
  --width: 300px;
}
* {
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  overflow: hidden;
  font-family: sans-serif;
}

.slider-content-box {
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.slide-outer{
  width: var(--width);
  background: #4e6cf2;
  border-radius: 15px;
  box-shadow: 0px 0px 16px 5px rgba(0,0,0,0.3);
}
.slider {
  text-align: center;
  position: relative;
}

.slides {
  display: flex;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth;

}
.img-section {
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  border: none;
  outline: none;
}

.img-section img {
  height: 250px;
  width: 100%;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.slides>div {
  color: white;
  flex-shrink: 0;
  width: var(--width);
  height: auto;
  padding: 20px 10px 50px 10px;
  position: relative;
  display: flex;
  text-align: left;
  justify-content: center;
  align-items: center;
  font-size: 13px;
  font-weight: 400;
}
.slides>div:first-child{
  font-size: 20px;
  font-weight: 600;
}

.arrows {
  position: absolute;
  z-index: 1;
  display: inline-flex;
  column-gap: 10px;
  bottom: 18px;
  right: 25px;
}

.slider .arrows a {
  width: 1rem;
  height: 1rem;
  text-decoration: none;
  align-items: center;
  justify-content: center;
  position: relative;
}

.slider .arrows a img {
  height: 20px;
  width: 30px;
}

.non-active-arrow-right,
.non-active-arrow-left {
  display: none;
}

.slider-scroll-box{
  padding: 10px 0px;
}
.slides::-webkit-scrollbar {
  width: 10px;
  height: 2px;
  border-radius: 10px;
  margin: 0px 10px;
}

.slides::-webkit-scrollbar-thumb {
  background: #9c9c9c;
  border-radius: 10px;
  padding: 0 !important;
}

.slides::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 10px;
  margin: 0px 20px;
}

.blur-image{
  filter: brightness(0.5);
}
<div class="slider-content-box">
    <div class="slide-outer">
      <div class="img-section">
        <img src="https://fs.hubspotusercontent00.net/hubfs/20523656/Group%2024941.png" width="100%" height="200px">
      </div>
  
      <div class="slider-scroll-box">
        <div class="slider">
          <div class="arrows">
            <a href="#slide-1" id="image-1">
                <img src="https://fs.hubspotusercontent00.net/hubfs/20523656/left-arrow-active.svg" class="active-arrow-left">
            </a>
  
            <a href="#slide-2" id="image-2">
              <img src="https://fs.hubspotusercontent00.net/hubfs/20523656/right-arrow-active.svg" class="active-arrow-right">
            </a>
  
          </div>
          <div class="slides">
  
            <div id="slide-1">
              Hello, I'm <br> Joe. The dev <br> of
            </div>
            <div id="slide-2">
              lorem ispoumm lorem ispoumm lorem ispoumm lorem ispoummlorem ispoummlorem ispoumm lorem ispoumm
            </div>
  
          </div>
  
        </div>
      </div>
  
    </div>
  </div>

As you can see, I’m using hash links for the arrow buttons so that it moves from div to div. However, this doesn’t seem to be good practice because when it’s applied to a page, clicking the arrows prompts the viewport to jump where the arrows begin.

Is there a way to maybe disable the jumps within this div or the entire page? Would anyone have a different idea to get it to function the same but without the hash links?