see the characters’name with react setState Api on your page

hi everyone I hope you all have a great day.Well recently I tried to understand React and the problem is I wanna get some information and see it on page I can randomly see different characters by RandomNum and put it in the https of that site but the truth is I can see it only in console not the page where is my problem ? I would be happy if you could help me thanks.

import './App.css';

// import Item from './myItem'

import React from 'react';


class StarWars extends React.Component{

constructor(){
  super()
  this.state={
    loadedCharacter:false,
    name:null,
    height:null,
    homeworld:null,
    eye_color:null,

  }

}



newCharacterFromBtn(){
  
    const randomNum=Math.round(Math.random()*82)
    const url=`https://swapi-node.vercel.app/api/people/${randomNum}/`
     fetch(url)
      .then(response => response.json())
      .then(data =>{
        console.log(data)
       this.setState(
      { loadedCharacter:true,
        name:data.name,
        height:data.height,
        homeworld:data.homeworld,
        eye_color:data.eye_color,
        
      })
    
    })
    
  }
render(){
  return(
    <div>

      {
        this.state.loadedCharacter &&
        <div>
          <h1>name:{this.state.name}</h1>
          <p>height:{this.state.height}</p>
          <p>homeWorld:{this.state.homeworld}</p>
          <ul>
            <li>eyecolor:{this.state.eye_color}</li>
          </ul>
        </div>
      }
      
      <button onClick={()=> this.newCharacterFromBtn()} type="button" className="btn">Randomize Character</button>
    </div>
  )
}


}
function App() {
return (
  <div className="App">
    <header className="App-header">
      <StarWars />
    </header>
  </div>
);
}

export default App;





   ```

  








                                                                                                                                                                                                                                                                                                                 

How to validate form in client-side in React Router v7

I follow the Form Validation tutorial in React Router. But there isn’t a client-side form validation.

I try to use clientAction() for client-side validation.

export async function clientAction({ request }: Route.ClientActionArgs) {
  const formData = await request.formData();
  const formValues = {
    name: formData.get('name')
  };
  const validate = formSchema.safeParse(formValues);

  if (!validate.success) {
    return { errors: z.flattenError(validate.error) };
  }

  // { success: true, data: ... }
  // return ???
}

// server-side action()
export async function action({ request }: Route.ActionArgs) {
  const formData = await request.formData();
  const formValues = {
    name: formData.get('name'),
  };
  const validate = formSchema.safeParse(formValues);

  if (!validate.success) {
    return { errors: z.flattenError(validate.error) };
  }
  await db.insert(table).values(formValues);
  return redirect(href('/home'));
}

Then, how to execute action() after clientAction() for server-side validation? What should I return?

How do I break down my code into smaller and manageable chunks of modules?

I am learning JavaScript and I currently I am learning about modules. I have no idea how to do it. I do know that I have to use export and import to do it but I don’t know how I should proceed with it and how to make separate files for each module.

function select() {
    const add = document.querySelector(".add-btn");
    add.addEventListener("click", addItem);
}

function addItem() {
    const main = document.querySelector(".main");

    const newItem = document.createElement("div");
    const newHeading = document.createElement("h2");
    const deleteButton = document.createElement("button");
    const inputArea = document.createElement("input");

    newItem.classList.add("new-div");
    newHeading.classList.add("new-heading");
    deleteButton.classList.add("delete-btn");
    inputArea.classList.add("textbox");

    deleteButton.innerText = "Delete";
    inputArea.type = "text";
    inputArea.placeholder = "Enter here...";

    num = main.children.length;
    newHeading.innerText = `Task ${num}`;

    newItem.append(newHeading, deleteButton, inputArea);

    inputArea.addEventListener("keydown", ({ key }) => {
        if (key == "Enter" && inputArea.value.trim() != "") {
            const textValue = inputArea.value;

            const displayText = document.createElement("p");

            displayText.classList.add("txt-val");
            displayText.innerText = textValue;

            newItem.appendChild(displayText);
            newItem.removeChild(inputArea);
        }
    })

    document.querySelector(".main").appendChild(newItem);

    inputArea.focus();  /* this makes the text box appear with a blinking cursor by default */          

    deleteItem(deleteButton, newItem);

    num++;
}

function deleteItem(button, item) {
    button.addEventListener("click", () => {
        const main = document.querySelector(".main");
        main.removeChild(item);
    });
}

select();
*,
::before,
::after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

h1 {
    text-align: center;
    margin-top: 2em;
    text-decoration: underline;
    font-size: 3em;
}

.main {
    margin-top: 3em;
    border-right: 12px solid rgb(108, 179, 202);
    border-left: 12px solid rgb(108, 179, 202);
    border-top: 8px solid rgb(108, 179, 202);
    border-bottom: 8px solid rgb(108, 179, 202);
    height: 100%;
    position: relative;
}

.add-btn {
    background-color: rgb(74, 184, 74);
    color: white;
    font-weight: bolder;
    font-size: x-large;
    padding: 10px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    height: 2em;
    position: absolute;
    translate: -2.5em -1.1em;
    z-index: 1000;
}

.add-btn:hover {
    background-color: rgb(112, 219, 112);
    transition: 0.5s;
}

.main-button-class {
    text-align: center;
}

.new-heading {
    font-family: Georgia, 'Times New Roman', Times, serif;
}

.new-div {
    position: relative;
    border: 5px solid rgb(84, 153, 218);
    margin-top: 65px;
    margin-bottom: 30px;
    margin-left: 32px;
    margin-right: 32px;
    padding: 15px;
    height: 170px;
    text-align: center;

}

.delete-btn {
    width: 65px;
    height: 50px;
    background-color: red;
    color: white;
    font-weight: bold;
    font-size: large;
    border-radius: 10px;
    position: absolute;
    top: 0;
    right: 0;
    translate: 25px -25px;
    cursor: pointer;
    border: none;
}

.textbox {
    width: 95%;
    height: 80px;
    margin-top: 15px;
    padding: 15px;
    border: 1px solid black;
}

.txt-val {
    font-size: x-large;
    color: black;
    margin-top: 35px;
}

.delete-btn:hover {
    background-color: rgb(255, 105, 105);
    transition: 0.5s;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List New</title>
    <script defer src="/JavaScript/Todo List New.js"></script>
    <link rel="stylesheet" href="/CSS/Todo List New.css">
</head>
<body>
    <h1>Todo List</h1>
    
    <div class="main">
        <div class="main-button-class">
            <button type="button" class="add-btn">Add Task</button>
        </div>
    </div>
</body>
</html>

I have posted my code above. But I don’t know how to break down my JavaScript files into smaller chunks and how to bring them all together. I am also hesitant to do it because when I tried it on my own, the code didn’t work and the control flow got messed up.

React Router + Vite Layout Not Rendering Nested Route

I’m using @react-router/dev with Vite for file-based routing. I expect my layout component (AdminLayout) to render text on the route /admin/dashboard, but it’s not showing up — only the dashboard content appears.

app/
├── routes.ts
├── routes/
│ └── admin/
│ ├── admin-layout.tsx
│ └── dashboard.tsx

routes.ts

```import { type RouteConfig, route } from "@react-router/dev/routes";

export default [
  route({
    path: "admin",
    file: "routes/admin/admin-layout.tsx",
    children: [
      route({
        path: "dashboard",
        file: "routes/admin/dashboard.tsx"
      })
    ]
  })
] satisfies RouteConfig;```

admin-layout.tsx

```import { Outlet } from "@react-router/dev";

export default function AdminLayout() {
  console.log("Rendering AdminLayout");
  return (
    <div className="flex">
      <aside className="w-64 hidden lg:block">Sidebar</aside>
      <main className="flex-1">
        <Outlet />
      </main>
    </div>
  );
}```

The Problem: Visiting /admin/dashboard shows the dashboard, but not the layout content.
console.log(“Rendering AdminLayout”) doesn’t appear — so the layout component isn’t rendering.

Question:
Why isn’t AdminLayout rendering for the nested route? Am I missing something in my route config or setup?

Thanks in advance!

How to track multilingual button clicks in Yandex.Metrica with organization data?

I’m working on a multilingual website (with ru and uz locales) and trying to implement click tracking in Yandex.Metrica.

When a user clicks the “Show phone number” button on a university’s profile card, I want to send the following data to Metrica:

  • Organization name (e.g., “ABC University”)
  • Category (e.g., “university”, “school”, etc.)
  • Language (ru or uz)

Here’s what I’d like to achieve:

  • Count total clicks per organization, across all languages

  • Group reports by language, category, and organization

    const myParams = {
      [language]: {
        [organization.category]: organization.name[language]
      },
    };
    
    (window as any).ym?.(103200533, "reachGoal", "phone-click", myParams);
    

Webscrape with Node.js – Javascript with login

I have been scraping a investment site with Python and Selenium but due to changes needed to system I will no longer be able to use Python and only option I seem to have is Node.JS / NodeRed

Anyhow I seem to have managed to get the following to login to the site but what I get back is basically a blank page staying need Javascript. If I try to load one of the pages from the network list that comes up in Chrome Developer tools I get generally a 401 error.

Website I go to in a browser if I was to login is https://app.raizinvest.com.au/auth/login

I have found from the recording feature in chrome that this login information is “Posted” to “https://api.raizinvest.com.au/v1/sessions”

Back in the webbrowser it then takes me to a page “https://app.raizinvest.com.au/?activeTab=today” which displays my current funds among a bunch of other irrelevant stuff.

If I load that same page after my login in Node.js I get a Need Javascript page which if I look at the HTML of that page in the browser is what I see so I am happy I have logged in successfully.

What I need to know is how to get the info I want. If I look at the list of items in the network tab back in the browser there is an item account_summary with url reported as ‘https://api.raizinvest.com.au/mobile/v1/account_summary’ but if I try to load that page I get a 401 error. Likewise if I try to click on it in the browser I get an unauthorised error (See screenshot).

My script is as follows. Note: I have obviously changed my login details and the UDID I am just making random at the moment manually but I am aware there is a addon to dynamically make one

For context if relevant the output from the first console output it is a json with TOKEN and User_uuid. Not sure if this is remembered and transmitted automatically in the background of if I need to explicitly send it.

const superagent = require('superagent').agent()

const harvest = async () => {
    let dashboard = await superagent
        .post('https://api.raizinvest.com.au/v1/sessions')
        .send({email: 'fam...@outlook....', password: 'w5.....', udid: 'bc28eff9-0cf2-414d-a17b-01ec20d53bc3' })
        .set('Content-Type', 'application/json');
    console.log(dashboard.text);
    let dashboard2 = await superagent.get('https://app.raizinvest.com.au/?activeTab=today');
    console.log(dashboard2.text);
    let dashboard3 = await superagent.get('https://api.raizinvest.com.au/mobile/v1/account_summary');
    console.log(dashboard3.text);   

};

harvest();

Any advice on what to look at or into would be appreciated. I understand as it is behind a login it is difficult to solve but suggestions where I should look would be appreciated.

I tried what I have posted above and get a 401 error. Get the same though when I click that source object in Chrome so unsure what method to utilise to access it

Javascript Function Returns Null in ByRef Argument But Response has Value inside the function

The console.log(oResponse); of oResponse in the function mGetLookUpTableArray writes the information of the json_encoded object in the console log. There is data from the database in the oResponse object.

However console.log("aLookupTable: " + aLookupTable); does not output anything. The message in the console log is aLookupTable: null

So aLookupTable which is passed in as an argument when I call mGetLookUpTableArray is not getting populated in mGetLookUpTableArray. Any ideas?

  • Javascript Making The Call of the Below Function

    const sBasePath = ${window.location.protocol}//${window.location.host}${window.location.pathname.split(‘/’)[1] ? ‘/’ + window.location.pathname.split(‘/’)[1] + ‘/’ : ‘/’}`; // Outputs the base path, e.g., “https://example.com/subdirectory/”

    const sURL = sBasePath + “db_includes/get_tb_Lookup.php”;

         const aLookupTable = null;
         mGetLookUpTableArray(sURL, aLookupTable);
         console.log("aLookupTable:  " + aLookupTable);
    
  • Javascript Function Being Called

    function mGetLookUpTableArray(sURL, arrLookupTable) {
                     $.ajax({
                         url: sURL,    
                         type: 'Post',    
                         dataType: 'json',
    
                         success: function (oResponse) {
                             console.log(oResponse);
                             arrLookupTable = oResponse; 
    
                         },
                         error: function(oXHR, sStatus, oError) {
                             console.error('Error:', oError);
                             console.error('Status:', sStatus);
                             console.error('Response:', oXHR.responseText);
                         }
                     });
     }
    

PHP to Javascript conversion [closed]

I have a small PHP script that I’ve been using for quite some time to generate link menus. Now, I have to create a menu of links on a server that does not have PHP capabilities. Javascript has been recommended, but I am not literate in that language. So, I tried an online PHP to Javascript converter, and it was only partially successful. Below is the PHP that I’ve been using. It checks the URL for the page name and applies one of two CSS property sets, depending on whether or not it is the currently loaded page.

<?php
$pageName = basename($_SERVER['REQUEST_URI']);
?>

<li class="<?php if ($pageName=="page1.html") {echo "linksactive"; } else  {echo "linksinactive";}?>"><a href="page1.html">Page 1</a></li>
<li class="<?php if ($pageName=="page2.html") {echo "linksactive"; } else  {echo "linksinactive";}?>"><a href="page2.html">Page 2</a></li>
<li class="<?php if ($pageName=="page3.html") {echo "linksactive"; } else  {echo "linksinactive";}?>"><a href="page3.html">Page 3</a></li>

Here is what the converter supplied =>

const pageName = window.location.pathname;

document.write(`
    <li class="${pageName === '/page1.html'? 'linksactive' : 'linksinactive'}"><a href="page1.html">Page 1</a></li>
    <li class="${pageName === '/page2.html'? 'linksactive' : 'linksinactive'}"><a href="page2.html">Page 2</a></li>
    <li class="${pageName === '/page3.html'? 'linksactive' : 'linksinactive'}"><a href="page3.html">Page 3</a></li>
`);

By partially successful, I mean it constructs the link list, and it applies the CSS associated with “linksinactive”; however, it does not apply the CSS associated with linksactive, implying that it does not recognize the current, active page.

I tried many other online converters, and either the result was the same, or the output was blank, or in one case, it applied some of the linksactive CSS, but obliterated the rest of the webpage.

Finally, the javascript is run as an external script, as follows.

<ul style="list-style-type:none; padding-left:0;">
                    
<script type="text/javascript" src="./.js/hymnlist.js"></script>
                    
</ul>

What did the converter miss in translation? Thanks.

How to replicate this shutter reveal effect from this wix template?

I want to recreate this shutter reveal effect, in which as we scroll the hero section (the shutter) slides upwards and reveals the section below it, once the shutter is fully out of the viewport the scroll transfers to the rest of the website and we can scroll through the other sections (what I think happens).

Screenshot of the wix template shutter effect

Here is the link to the wix template: Link

I tried setting the animation timeline to scroll like this:

.hero-section {
  position: absolute;
  height: 100vh;
  width: 100%;
  z-index: 1;
  animation: uncover linear;
  animation-timeline: scroll();

  @keyframes uncover {
    to {
      transform: translateY(-100%);
    }
  }
}

but the problem here was when I scroll the hero section goes up but the sections under it also scroll up but at a normal speed (slower than hero section). Instead I want the content beneath the hero section to be static until the hero section is completely out of viewport.

Ways to support joins on elasticsearch

I’m working with two Elasticsearch indexes -> accounts and contacts. These indexes are related in such a way that each account can be associated to contacts. However, not all contact data is denormalized into the accounts index.
Now I need to query accounts and filter the results based on some fields present only in the associated contacts index. This essentially requires a join-like behavior across two indexes.

Constraints:

Both indexes have multiple shards, so I can’t use lookup-joins provided by elasticsearch, as it currently supports single shard capability.

I also cannot use data enrichment either because the data in both indexes changes frequently, and keeping enrich policies updated in near real-time is not practical.

A full denormalization isn’t ideal either due to data duplication and sync complexity.

cookie get deleted after page refresh

Issue – cookie is getting deleted when page is refresh but cookie was successfully set from backend (Express).

Requesting API call using Axios in React.

Below is my express code :

CORS configurations :

app.use(cors({
    origin: 'http://localhost:5173',
    credentials: true
}));

Cookie set :

res.cookie("token", "mygeneratedtoken", { expires: new Date(Date.now() + 8 * 3600000) });
res.send(userInfo);

Front end code :

try {
      const response = await axios.post(
        `http://localhost:5173/login`,
        {
          emailId,
          password,
        },
        {
          withCredentials: true,
        }
      );
      dispatch(addUser(response.data));
      navigate("/");
    } catch (err) {
      console.log("Error : " + err.message);
    }

enter image description here

warning on same site

enter image description here

Please help me to resolve this problem.

How to reference an image directly? [closed]

How do I reference an image directly. What I mean is if I have

export default function ExamplePage() {
    return (
        <img src='some-image.png'>
    );
}

It will be a blank website with the image, instead of the image itself. I need to reference the image because this is used by the application to download images directly based on the GET parameters. How can I do this in react?

Reference image directly with react

How do I reference an image directly. What I mean is if I have

export default function ExamplePage() {
    return (
        <img src='some-image.png'>
    );
}

It will be a blank website with the image, instead of the image itself. I need to reference the image because this is used by the application to download images directly based on the GET parameters. How can I do this in react?

Testing for a particular date works locally, but not on GitHub

The task is to check if a certain date is a statutory holiday, by comparing a date against a list of known statutory holiday dates.

Here is the JSON list of stat holidays:

{
    "provinces": [
        {
            "name": "Ontario",
            "statutory": [
                {
                    "name": "Christmas",
                    "date": "2025-12-25"
                },
            ]
        ...

Here is the test:

describe("statHoliday", () => {
  test("should identify statutory holiday", () => {
    const statDay = new Date("2025-12-25T10:00:00.000");
    expect(isStatHoliday(statDay)).toBe(true);
  });
});

Here is the function to test the date:

function isStatHoliday(date) {
  const dateObject = new Date(date);
  const dateString = dateObject.toLocaleDateString();

  // "theProvince" here is set to Ontario 
  return !!theProvince.statutory.find(holiday => holiday.date === dateString);
}

When testing locally, this works fine. When I upload to GitHub, and the tests are run there, it fails:

Expected: true
Received: false

I assume this has something to do with time zones, specifically the routine toLocaleDateString(), but I’m not sure how to correct this. Locally, I am GMT-4, and I assume the GitHub server is in UTC?

Почему при последующих рендерах ширина правильная у второго элемента, а при первом нет? (ReactJS, useLayout, useRef) [closed]


Имеется такой код, при использовании useLayoutEffect, он должен подсчитать мне ширину каждого option, и при нажатии добавить ширину предшествующих элементов, чтобы выбрать текущий option, но при добавлении первых рендеров значение 2-го элемента 114, хотя должно быть 123, как это можно исправить?

import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";

type SelectProps = {
    options: string[]
}

const Select = ({
    options
}: SelectProps) => {
    const [currentOption, setCurrentOption] = useState(0);
    const ref = useRef(null);
    const [x, setX] = useState(0);
    const [widthElements, setWidthElements] = useState([0])
    const currentWidth = widthElements[currentOption + 1]
    
    const handleChangeOption = (index: number) => {
        setCurrentOption((prev) => prev = index)
        setX(widthElements.slice(0, index + 1).reduce((acc, el) => acc + el))
    }

    useLayoutEffect(() => {

        if (ref?.current?.children) {
            const widths = [...ref?.current?.children].map((value: HTMLElement) => value.offsetWidth)
            setWidthElements([0, ...widths])
        }
        console.log(widthElements)
        
    }, [currentWidth])
    
    
    return (
        <div className="relative bg-black-20 max-w-80 md:max-w-[368px] h-14 p-2 rounded-[0.5rem]">
            <div ref={ref} className="absolute flex z-1">
                {options.map((option, index) => (
                    <div
                        key={index + option}
                        className={`relative ${currentOption === index ? 'text-primary-50' : 'text-gray-300'} 
                        px-8 py-2 rounded-[0.5rem] link-regular text-xs md:text-base transition-all duration-200 ease-in-out
                        
                        `}
                        onClick={() => handleChangeOption(index)}
                    >
                        {option}
                    </div>
                ))}
            </div>
            <div className="relative w-full h-full overflow-hidden ">
               <div
                    style={{
                        width: currentWidth + 'px',
                        transform: `translateX(${x}px)`
                    }}
                    className={`absolute top-0 left-0 h-10 bg-primary-300 text-primary-50 rounded-[0.5rem]
                transition-all ease-in-out duration-200
            `} />

            </div>

        </div>)
}

export default Select;