how to add click able element on react js using array type of jsx.element?

id like to make my react js element to clickable component on an arraytype component using JSX.Element but it seems wrong
ive done on first index on id:1 the href tag but its not opening external links
here is my code:

const Movies: React.FC = () => {  
  const getMovies = (): JSX.Element[] => {
    return [{
      desc: "A tale of some people watching over a large portion of space.",
      id: 1,
      icon: "fa-solid fa-galaxy",
      href: "www.wikipedia.com",
      image: "https://images.unsplash.com/photo-1596727147705-61a532a659bd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8bWFydmVsfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60",
      title: "Protectors of the Milky Way"
    }, {
      desc: "Some people leave their holes to disrupt some things.",
      id: 2,
      icon: "fa-solid fa-hat-wizard",
      image: "https://images.unsplash.com/photo-1535666669445-e8c15cd2e7d9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bG9yZCUyMG9mJTIwdGhlJTIwcmluZ3N8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60",
      title: "Hole People"
    }, {
      desc: "A boy with a dent in his head tries to stop a bad guy. And by bad I mean bad at winning.",
      id: 3,
      icon: "fa-solid fa-broom-ball",
      image: "https://images.unsplash.com/photo-1632266484284-a11d9e3a460a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fGhhcnJ5JTIwcG90dGVyfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60",
      title: "Pot of Hair"
    }, {
      desc: "A long drawn out story of some people fighting over some space. Cuz there isn't enough of it.",
      id: 4,
      icon: "fa-solid fa-starship-freighter",
      image: "https://images.unsplash.com/photo-1533613220915-609f661a6fe1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8c3RhciUyMHdhcnN8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60",
      title: "Area Fights"
    }].map((movie: any) => {
      const styles: React.CSSProperties = {
        backgroundImage: `url(${movie.image})`  
      }
      
      const id: string = `movie-card-${movie.id}`;
      
      return (
        <div key={movie.id} id={id} className="movie-card">
          <div class="container" className="movie-card-background background-image" style={styles} /><a href="https://www.w3docs.com/"></a><span class="link"></span>
          <div className="movie-card-content">
            <div className="movie-card-info">
              <span className="movie-card-title">{movie.title}</span>
              <span className="movie-card-desc">{movie.desc}</span>
              <span classNAme="movie-card-href">{movie.href}</span>
            </div>
            <i className={movie.icon} />
          </div>
        </div>
      );
    })
  }

as u see im copying this code for my webs and still learning abour react js
thanks

clickable react js element

Why does Instagram user agent change slightly?

I’ve been seeing some requests to my site where the user agent has Instagram in it, but the user agent changes slightly from the same IP and also the cookies then change.

The only thing that changes is that a “NW/3” string is appended on the end at the beginning and then it changes.

Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Instagram 191.0.0.25.122 (iPhone13,1; iOS 14_4_2; en_CA; en-CA; scale=2.88; 1080×2338; 296543649) NW/3

I thought maybe it is a malicious users because all of the cookies change right when the header changes, but I’m not 100% confident.

I tried searching Google but nothing came up, anyone seen this before and know what it is?

The This keyword in Javascript make me confused, when I write it on browser console and the js file [duplicate]

I’m a beginner of Javascript. So I need someone help me, maybe my quesion is quite silly 🙁
The question is:
When I learn about the This keyword in Javascript, I know it will be undefined when I call a regular function like the following code:

const f = function() {
  console.log(this);
}

f();
type here

I expect this code will be the same when I write it in both my file.js and the browser console. But the answer is NO. When I write it in my file.js and run by the browser, the result is undefined; but when I write it directly on the browser console, it’s the Window object. I don’t understand why it works like that. So please give me some helpful answers. Thanks!!!

How to maintain checkbox state across pages using React and localStorage?

I have a project where I’m trying to have an array of books, and each book has an option to be marked as “TBR” with a slider / checkbox. It is then moved to a different page (TBR Page) where it’s shown with an array of other books that are also TBR. My issue is that once marked as TBR, once you go to look at the book again, it is no longer marked as TBR, so you can add it to the list over and over again. I’d like for it to stay marked. I’m trying to use localStorage for this, but it’s my first time using it.

Below is the book description page where the checkbox is.
[id].js

import { useRouter } from 'next/router';
import Form from 'react-bootstrap/Form';
import { useEffect, useState } from 'react';
import { getSingleBook } from '../api/promises';
// import useLocalStorage from '../utils/useLocalStorage';

function ViewBook() {
  const [viewBook, setViewBook] = useState([]);
  const [tbr, setTbr] = useState(false);
  // const [read, setRead] = useState(false);
  // const [reading, setReading] = useState(false);
  const router = useRouter();
  const { id } = router.query;

  useEffect(() => {
    getSingleBook(id).then(setViewBook);
  }, [id]);

  const addToTbr = () => {
    router.push({
      pathname: '/TBR',
      query: {
        book: JSON.stringify(viewBook),
        tbr: tbr ? 'true' : 'false',
      },
    });
    if (tbr) {
      // Add the book to TBR
      const savedTbrBooks = localStorage.getItem('tbrBooks');
      const parsedTbrBooks = savedTbrBooks ? JSON.parse(savedTbrBooks) : [];
      const updatedTbrBooks = [...parsedTbrBooks, viewBook];
      localStorage.setItem('tbrBooks', JSON.stringify(updatedTbrBooks));
    } else {
      // Remove the book from TBR
      const savedTbrBooks = localStorage.getItem('tbrBooks');
      if (savedTbrBooks) {
        const parsedTbrBooks = JSON.parse(savedTbrBooks);
        const updatedTbrBooks = parsedTbrBooks.filter((book) => book.id !== viewBook.id);
        localStorage.setItem('tbrBooks', JSON.stringify(updatedTbrBooks));
      }
    }
  };

  useEffect(() => {
    if (tbr) {
      addToTbr();
    }
  }, [tbr]);

  useEffect(() => {
    localStorage.setItem('tbrState', tbr ? 'true' : 'false');
  }, [tbr]);

  useEffect(() => {
    const savedTbrState = localStorage.getItem('tbrState');
    if (savedTbrState !== null && savedTbrState !== '') {
      setTbr(savedTbrState === 'true');
    }
  }, []);

  useEffect(() => {
    localStorage.setItem('tbrState', tbr ? 'true' : 'false');
  }, [tbr]);

  const handleTbrToggle = (e) => {
    const isChecked = e.target.checked;
    setTbr(isChecked);
  };

  console.warn(viewBook);

  return (
    <>
      <img
        src={viewBook?.volumeInfo?.imageLinks?.smallThumbnail}
        style={{
          height: '500px',
          width: '300px',
        }}
        alt=""
      />
      <Form.Check
        className="text-white mb-3"
        type="switch"
        id="tbr"
        name="tbr"
        label="TBR"
        checked={tbr}
        onChange={handleTbrToggle}
      />
      <h1>{viewBook?.volumeInfo?.title}</h1>
      <p>{viewBook?.volumeInfo?.authors}</p>
      <p>{viewBook?.volumeInfo?.description}</p>
    </>
  );
}

export default ViewBook;

This is the TBR Page.
TBR.js

import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import BookCard from '../components/BookCard';

export default function TBRPage() {
  const router = useRouter();
  const { book, tbr } = router.query;

  const [parsedBooks, setParsedBooks] = useState([]);

  useEffect(() => {
    // Retrieve the TBR books from local storage
    const savedTbrBooks = localStorage.getItem('tbrBooks');

    if (savedTbrBooks) {
      const parsedTbrBooks = JSON.parse(savedTbrBooks);
      setParsedBooks(parsedTbrBooks);
    }
  }, []);

  useEffect(() => {
    if (Array.isArray(book)) {
      setParsedBooks(book.map((bookObj) => JSON.parse(bookObj)));
      // localStorage.setItem('tbrBooks', JSON.stringify(book));
    } else if (book) {
      setParsedBooks([JSON.parse(book)]);
      // localStorage.setItem('tbrBooks', JSON.stringify([book]));
    }
  }, [book]);

  return (
    <>
      {parsedBooks?.map((parsedBook) => (
        <BookCard bookObj={parsedBook} key={parsedBook.id} />
      ))}
    </>
  );
}

I’ve been trying to use localStorage here but I can’t seem to get it right because it’s my first go.

draggable position:absolute div shrinking after hitting edge of position:relative div?

I have two draggable divs with position:absolute positioned inside of a position:relative div. My problem is that when I drag my divs to the edge of the position:relative parent they start to shrink. I need my draggable divs to stay the same size when they leave the parent’s container, but I have no idea how to fix this issue.

Here’s my codepen with the problem

    <div id="all">
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
    </div>
    <script src="move.js"></script>
* {
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    line-height: 1.1;
    margin: 0;
}

#all {
    position: relative;
    margin: 0 auto;
    width: 50%;
    height: 100vh;
}

.move {
    cursor: move;
    position: absolute;
}

.txtbox, .topper {
    background-color: lightgrey;
}

.txtbox {
    min-height: 70px;
    max-width: 250px;
}

.topper {
    font-size: .625em;
    border-bottom: 1px solid black;
    padding: 2px;
}
const els = document.querySelectorAll(".move");
els.forEach((name) => {
  dragElement(name);
});

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }
  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = elmnt.offsetTop - pos2 + "px";
    elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
  }
  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

Getting transaction count from RPC with Flashbots provider and signers results in hex > 64 bits error. How can I fix it?

Error: Processing response error(body=”{“jsonrpc”:”2.0″,”id”:44,”error”:{“code”:-32602,”message “:”invalid argument 1: hex > 64 bits”}}”, error={“code”:-32602}, requestBody=”{“method”:”eth_getTransactionCount”,”params”:[“xbb2f031ba8e4054c6deb595e0cc8a0350355c85″,”0xbb2f031ba8e4054c6deb595e0cc8a0350355c85″],”id”:44,”jsonrpc”:”2.0″}”, requestMethod =”POST”, url=”https://rpc.ankr.com/eth/60aa9cfcf046ce2599df4fd3fc5800ff8dbb4eab9ac032ae99f13e07ad66ffcc”, code=SERVER_ERROR, version-web/5.7.1)
at Logger.makeError (D:NFT ProjectsThe AccountantThe-Accountantnode_modules@ethersprojectloggersrc.tsindex.ts:269:28)
at Logger.throwError (D:NFT ProjectsThe AccountantThe-Accountantnode_modules@ethersprojectloggersrc.tsindex.ts:281:20)
at D:NFT ProjectsThe AccountantThe-Accountantnode_modules@ethersprojectwebsrc.tsindex.ts:341:28
at step (D:NFT ProjectsThe [email protected]:33:23)
at Object.next(D:NFT ProjectsThe [email protected]:14:53)
at fulfilled (D:NFT ProjectsThe [email protected]:5:58)
at processTicksAndRejections(node:internal/process/task_queues:96:5)

I’m trying to set up the flashbots provider with signers, but I keep getting errors.
I’ll share a screenshot of the error below. But basically I’m trying to get the transaction count from RPC, but I can’t seem to do that.

Excuse the confusion of provider js.

tried a lot

The error in the screenshot is from the transaction function on line 53 after signing, but there are a few other issues that I believe may be related to the ethers js. But I’m not too sure.

The reason for why componentWillMount is not ok for side effects

Sure, componentWillMount is not something talk about now due to it being obsolete but I came across the react docs and it says that

componentWillMount is called before render which means setting state
synchronously in componentWillMount will not cause extra render call.

Is it true that setState will not work in that lifecycle method at all?

Cyclcic imports fix. Dependency cycle detected

Consider this short snippets in each of its files.

// a.ts
import { getModuleB } from "./auxiliaryModule";

export const a = 2;

const b = getModuleB();
console.log(b);

// b.ts
import { getModuleA } from "./auxiliaryModule";

export const b = 1;

const a = getModuleA();
console.log(a);

// auxiliaryModule.ts
import { a } from "./a";
import { b } from "./b";

export const getModuleA = () => {
  return a;
};

export const getModuleB = () => {
  return b;
};

I created the auxiliaryModule to get rid of the Dependency cycle detected error by trying to “Move the shared code into a third module” as suggested in the documentation. However the error does not go away.

What is the solution to remove this error and the pattern to use code from two modules interchangeably and safely?

What could be causing a sudden 404 error when navigating to routes on my Vue 3 JS test server?

I am developing a project on vue 3 js. When i am working on my localhost, there is no error. I made all routes. When browser catch a error, it is redirected to my home page. when i run my project at test server, with buttons i can change route but when i change routes on browser’s search bar or i refresh url on search bar i get 404 not found error. But i am sure that route is working and i can go that route in project with buttons. However i can’t refresh or go other routes on search bar. It suddenly throws 404 error. It is too fast it is like throwing 404 error without looking at which page. It behaves like all page doesn’t exist when you are refreshing or going some routes on search bar. I am new at vue 3 js or web development. This is my first project on outside of localhost. So i have no idea.

I am refreshing or going other routes on browsers search bar. I got 404 page not found error suddenly like it doesn’t exist.I am expecting i can go or refresh url on search bar

useEffect question I’ve been trying to understand

So I’ve been introduced to useEffect hook. As far as I understand, useEffect is used to prevent infinite loop in running setState function. But what I don’t understand is why is useEffect used to wrap the function which includes setting window height state with resize event listener. It does not give infinite loop. I’ve been trying to understand this and I would really appreciate if you help me out.Sorry for English(not my first language)

how to store appointments inside array without start and end time overlapping

problem statement

i need to push new appointment inside this array but, i also DONOT want to overlap time of other already booked appointment

my array

Booked appointment contains previously added/booked appointments!

Allappointments= [
{
“startDay”: 0,
“endDay”: 7,
“Booked Appointments”: [
{
“startTime”: 1530,
“endTime”: 1700
},
{
“startTime”: 1030,
“endTime”: 1300
}
]
}
];

half solution

i have managed to get this solution so far which which which works for start and end time,
But doesnt cover the start and end Day part,
day start with 0 and 7, covering whole week!

function validateTimeFrame(newTimeFrame, existingTimeFrames) {
const { startTime, endTime } = newTimeFrame;

    // Check for intersection with existing time frames
    const hasIntersection = existingTimeFrames.some((timeFrame) =>
      (startTime >= timeFrame.startTime && startTime <= timeFrame.endTime) ||
      (endTime >= timeFrame.startTime && endTime <= timeFrame.endTime)
    );
  
    // Check if it is encompassed by another time frame
    const isEncompassed = existingTimeFrames.some((timeFrame) =>
      startTime >= timeFrame.startTime && endTime <= timeFrame.endTime
    );
  
    // Check if it encompasses another time frame
    const encompasses = existingTimeFrames.some((timeFrame) =>
      startTime <= timeFrame.startTime && endTime >= timeFrame.endTime
    );
  
    return {
      hasIntersection,
      isEncompassed,
      encompasses
    };
  }
  
  // Example usage:
  const existingTimeFrames = [
    { startTime: 9, endTime: 10 },
    { startTime: 12, endTime: 14 },
    { startTime: 16, endTime: 18 }
  ];
  
  const newTimeFrame = { startTime: 11, endTime: 13 };
  
  const validationResult = validateTimeFrame(newTimeFrame, existingTimeFrames);
  console.log(validationResult);
  

Can’t grab info from my .json file into my .ejs pages

Can’t grab info from my .json file into my .ejs pages.

Kinda desperate here, tried a bunch of different stuff, nothing gets this to work
Here’s the register and login processes, everything here seems to be working fine, it stores stuff in the .json file no problem. But when I try to grab anything from that file, it just doesn’t.

Register:

app.post('/processa_registo', function (req, res) {


    var username = req.body.username;
    var password = req.body.password;
    
   
    if (username && password) {
        
        var registoUtilizador = { 'username': username, 'password': sha1(password), };
        var registosFicheiro = new Array();

        try {
            var dadosFicheiro = fs.readFileSync('dados.json', 'utf-8');
            registosFicheiro = JSON.parse(dadosFicheiro);
            // se, por algum motivo, o ficheiro não continha um array JSON...
            if (!Array.isArray(registosFicheiro)) {
                registosFicheiro = new Array();
            }
        }
        catch (error) {
            console.error('ficheiro inexistente ou sem registos anteriores');
            registosFicheiro = new Array();
        }

        var usernameExistente = false;
        for (var i = 0; i < registosFicheiro.length; i++) {
            if (registosFicheiro[i].username == registoUtilizador.username) {
                usernameExistente = true;
                break;
            }
        }
        if (!usernameExistente) {
            registosFicheiro.push(registoUtilizador);
            var dadosFicheiro = JSON.stringify(registosFicheiro);
            var sucesso = true;
            try {
                fs.writeFileSync('dados.json', dadosFicheiro);

            }
            catch (error) {
                console.error('erro ao guardar o registo');
                console.error(error);
                sucesso = false;
            }
            if (sucesso) {
                mensagem = 'registo adicionado';
            }
            else {
                console.error('erro')
            }
            
        }
    }
    else {
        //html += '<p>por favor, preencha os dados todos</p>n';
        mensagem = 'por favor, preencha os dados todos';
    }
    res.render('Pages/LogIn');
});

LogIn:

app.get('/processa_login', function (req, res) {
    var username = req.query.username;
    var password = req.query.password;
    if (username && password) {

        var registoUtilizador = { 'username': username, 'password': sha1(password) };
        var registosFicheiro = new Array();

        try {
            var dadosFicheiro = fs.readFileSync('dados.json', 'utf-8');
            registosFicheiro = JSON.parse(dadosFicheiro);
            if (!Array.isArray(registosFicheiro)) {
                registosFicheiro = new Array();
            }
        }
        catch (error) {
            console.error('ficheiro inexistente ou sem registos anteriores');
            registosFicheiro = new Array();
        }

        var utilizadorAutenticado = false;
        for (var i = 0; i < registosFicheiro.length; i++) {
            if (registosFicheiro[i].username == registoUtilizador.username && registosFicheiro[i].password == registoUtilizador.password) {
                utilizadorAutenticado = true;
                break;
            }
        }
    }
    res.render('pages/Profile');
});

Here’s the code for the actual .ejs page:

app.get('/Profile', function (req, res) {
    if (req.session.username) {
        var registosFicheiro = new Array();
        var registoUtilizador = null;
        try {
            var dadosFicheiro = fs.readFileSync('dados.json', 'utf-8');
            registosFicheiro = JSON.parse(dadosFicheiro);
            if (!Array.isArray(registosFicheiro)) {
                registosFicheiro = new Array();
            }
        }
        catch (error) {
            console.error('ficheiro inexistente ou sem registos anteriores');
            registosFicheiro = new Array();
        }
        if (registosFicheiro.length > 0) {
            for (var i = 0; i < registosFicheiro.length; i++) {
                if (registosFicheiro[i].username == req.session.username) {
                    registoUtilizador = registosFicheiro[i];
                    break;
                }
            }  
        }
    }
    username=username
    res.render('Pages/Profile', {registoUtilizador: registoUtilizador});
});
<%- include('../partials/Header') %>

    <div id="contentor" class="container-fluid">
      <div class="row">
        <div id="title">
        </div>
        <%= username %>
        <div id="conteudo" class="col-sm-8">
            <div id="barraqdizpost">
                <p>Post</p>
            </div>
            <div id="carousel" class="carousel slide" data-ride="carousel">
                <div class="carousel-inner">
                  <div class="carousel-item active">
                    <img class="d-block w-100" src="Imagens/PlaceHolder.jpeg" alt="First slide">
                  </div>
                  <div class="carousel-item">
                    <img class="d-block w-100" src="Imagens/PlaceHolder.jpeg" alt="Second slide">
                  </div>
                  <div class="carousel-item">
                    <img class="d-block w-100" src="Imagens/PlaceHolder.jpeg" alt="Third slide">
                  </div>
                </div>
                <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
                  <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                  <span class="sr-only">Previous</span>
                </a>
                <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
                  <span class="carousel-control-next-icon" aria-hidden="true"></span>
                  <span class="sr-only">Next</span>
                </a>
              </div>
        </div>
        <%- include('../partials/Sidebar') %>
    </div>
    </div>
      
    <%- include('../partials/Footer') %>  

All the variables are written in Portuguese since that’s how my college teacher though me, hope it doesn’t make it harder to help.

I’ve tried creating a separate .js file, wrote the <%= username %> segment in any way I could think of, and a combination of stuff similar to this

app.get('/', function (req, res) {
    var name = "Louise";
    // Render index page
    res.render('pages/index', {
        // EJS variable and server-side variable
        name: name
    });
});

can’t get Token on frontend for userAuth but everything works fine on my backend as I tested it with insomnia (MERN app)

I always get false for isLoggedIn on my fontend but everything is fine on my backend.

backend loginstatus function:

const loginStatus = asyncHandler(async (req, res) => {
  const token = req.cookies.token;
  if (!token) return res.json(false);

  //Verify Token
  const verified = jwt.verify(token, process.env.JWT_SECRET);
  if (verified) return res.json(true);

  return res.json(false);
});

on frontend:

export const getLoginStatus = async () => {
  try {
    const response = await axios.get(`${BACKEND_URL}/api/users/loggedin`);
    return response.data;
  } catch (error) {
    const message =
      (error.message && error.response.data && error.response.data.message) ||
      error.message ||
      error.toString();
    toast.error(message);
  }
};

I tried login from frontend and the backend always sends false as a response for loginStatus

Can’t send GET request from local HTML file to server [duplicate]

Whenever I try to send a GET request from JS in an HTML file I get the following error: Access to XMLHttpRequest at 'http://0.0.0.0:8080/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I looked around and apparently I’m supposed to put the HTML file in a server instead of my local machine.

But I’m using this HTML file as the UI of my app, so I can’t store it in a server. Instead I want the local HTML to send a GET request to a server and get back the result.

This is the code I used to send:

<script type = "text/javascript">
   function get_result()
   {
      let xmlHttp = new XMLHttpRequest();
      let query = document.getElementById("query-text-box").value;
      xmlHttp.open("GET", "http://0.0.0.0:8080/", false);
      xmlHttp.send(query);
      document.getElementById("result").innerHTML = xmlHttp.responseText;
   }
</script>