Detect hash code change in URL with NextJS 12

I can’t detect # hash code changes in URL with any of the useRouter props as useEffect dependancy:

  const { locale, asPath, basePath, pathname, route, query } = useRouter();
  const [hashCode, setHashCode] = useState<number>(1);

  useEffect(() => {
    console.log("Hash code changed");
    if (asPath.split("#")) setHashCode(Number(asPath.split("#")[1]));
    else {
      setHashCode(1);
    }
  }, [asPath, pathname, basePath, route, query]);

   return (  
   <>
     <a href="1">
        Hash code 1
     </a> 
     <a href="2">
        Hash code 2
     </a> 
   </> 

How can I detect hash code in the URL has been changed and set the current hash code in a state with Next JS ?

AgGridReact Pagination Dropdown Overlapping with Table – CSS Z-index Not Effective

I’m using AgGridReact for a table in my project, and I’ve encountered an issue where the pagination dropdown is overlapping with the table content and isn’t properly visible. I tried to inspect the HTML elements to adjust the CSS, but I’m unable to see the dropdown options in the inspection tools, presumably because they are dynamically generated.

Here’s what the problematic UI looks like: (You could attach your image here)

I’ve attempted several CSS fixes including adjusting the z-index and modifying the position of the dropdown, but none of these changes seem to have any effect. Here are some examples of what I tried:

.ag-paging-panel {
    z-index: 1000;
}

.ag-paging-page-size-panel select {
    position: relative;
    top: -10px;
}

.ag-paging-panel {
    overflow: visible;
}

Questions:
1.How can I ensure the dropdown is not obscured or overlapping with other elements?
2.Are there any specific styles or classes in Ag-Grid that I should target to fix this issue?
3.Could this be a bug with AgGridReact or am I missing something in my CSS adjustments?
Any help or insights would be greatly appreciated!

Smooth Scroll Behavior Not Working in React Application

I’m facing an issue with implementing smooth scroll behavior in my React application. Despite trying multiple methods, the smooth scrolling effect is not working. I’ve attempted to apply smooth scrolling via CSS and JavaScript, but without success. I’ve also tested in different browsers, but the result remains the same.

Here is what I’ve tried so far:

1)CSS for Smooth Scrolling:

@import url(“https://fonts.googleapis.com/css2?family=Dancing+Script&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900&family=Ubuntu+Mono&display=swap”);


* {
  margin: 0;
  padding: 0;
  font-family: "Roboto", sans-serif;
  box-sizing: border-box;
  text-decoration: none;
  scroll-behavior: smooth;
}

html, body {
  scroll-behavior: smooth;
}

2)React Component with HashLink:

import React from "react";
import { Link } from "react-router-dom";
import { HashLink } from "react-router-hash-link";

const Header = () => {
  return (
    <nav>
      <h1>TechyStar.</h1>
      <main>
        <HashLink to={"/#home"}>Home</HashLink>
        <Link to={"/contact"}>Contact</Link>
        <HashLink to={"/#about"}>About</HashLink>
        <HashLink to={"/#brands"}>Brands</HashLink>
        <Link to={"/services"}>Services</Link>
      </main>
    </nav>
  );
};

export default Header;

3)JavaScript Solution in React Component:

import React, { useEffect } from "react";
import { Link } from "react-router-dom";
import { HashLink } from "react-router-hash-link";

const Header = () => {

  useEffect(() => {
    // Add event listener for smooth scrolling
    const handleScroll = (event) => {
      event.preventDefault(); // Prevent default anchor click behavior
      const targetId = event.currentTarget.getAttribute("href").slice(1);
      const targetElement = document.getElementById(targetId);
      if (targetElement) {
        targetElement.scrollIntoView({
          behavior: "smooth",
          block: "start",
        });
      }
    };

    const aboutLink = document.querySelector('a[href="#about"]');
    if (aboutLink) {
      aboutLink.addEventListener("click", handleScroll);
    }

    // Cleanup the event listener on component unmount
    return () => {
      if (aboutLink) {
        aboutLink.removeEventListener("click", handleScroll);
      }
    };
  }, []);

  return (
    <nav>
      <h1>TechyStar.</h1>
      <main>
        <HashLink to={"/#home"}>Home</HashLink>
        <Link to={"/contact"}>Contact</Link>
        <HashLink to={"/#about"}>About</HashLink>
        <HashLink to={"/#brands"}>Brands</HashLink>
        <Link to={"/services"}>Services</Link>
      </main>
    </nav>
  );
};

export default Header;

The smooth scrolling effect is not working on my navigation links when I try to scroll to different sections on the page.
I’ve ensured that IDs are correctly set for each target section, and I’ve tested the behavior across different browsers.

Sudoku Solvable? [closed]

Is it possible to check whether a sudoku is solvable or not. I recently tried leetcode-36. But it only checks if the sudoku was valid, but i want to check for its solvability.
I designed a algorithm using backtracking, it checks for its validity and then solves the sudoku. For example if I gave sudoku that is unsolvable but is valid, it would check all 9^81 possibilities and then conclude it is not solvable. 9^81 is a huge number and my taking lots of time to give the result that sudoku is unsolvable.
For example check this sudoku, which is valid but unsolvable.
I want to know whether there is any algorithm that checks for sudoku to be solvable, or any such optimizations in backtracking that can be made to solve this issue.

i tried this code in js (I am designing a website for sudoku game)

function isSafe(matrix, row, col, num) {
    for (let x = 0; x < 9; x++) {
        if (matrix[row][x].value === num || matrix[x][col].value === num ||
            matrix[3 * Math.floor(row / 3) + Math.floor(x / 3)][3 * Math.floor(col / 3) + x % 3].value === num) {
            return false;
        }
    }
    return true;
}

function solveSudoku(matrix) {
    let empty = findEmptyLocation(matrix);
    if (!empty) {
        return true;
    }
    let row = empty[0];
    let col = empty[1];

    for (let num = 1; num <= 9; num++) {
        if (isSafe(matrix, row, col, num)) {
            matrix[row][col].value = num;
            if (solveSudoku(matrix)) {
                return true;
            }
            matrix[row][col].value = 0;
        }
    }
    return false;
}

function findEmptyLocation(matrix) {
    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            if (matrix[row][col].value === 0) {
                return [row, col];
            }
        }
    }
    return null;
}

How to properly track TextInput changes from child element to parent element in React Native?

I have developed a basic Search Bar component in my React Native project, and I would like to store the user’s search query in my parent element, and display this search query within the Search Bar. This is what I have so far:

Child Search Bar Component

import {Text, View, TextInput} from 'react-native'
import React from 'react'

const SearchBar = ({data, setData, setResult, filter, limit, value}) => {
  const filterList = (search) => {
    let filtered = data.filter((item) => item[filter].toLowerCase().includes(search.toLowerCase()))
    if(limit) {
      filtered = filtered.slice(0, limit)
    }
    setData(filtered)
    setResult(search)
  }

  return (
    <View className="mt-2 w-full h-10 px-2 bg-gray-300 border-2 border-black-200 focus:border-secondary flex flex-row items-center">
      <TextInput className="flex-1 text-black font-psemibold bg-gray-300" value={value} onChangeText={(search) => filterList(search)} clearButtonMode='always'/>
    </View>
  )
}

export default SearchBar

Parent Component

import { Text, View, Button, ScrollView, TouchableWithoutFeedback } from 'react-native'
import React, { useState, useEffect } from 'react'
import Header from '../components/Header.jsx';
import { router, useFocusEffect } from 'expo-router';
import { get_users_friends } from '../services/profile.js'
import FormField from '../components/FormField.jsx';
import SearchBar from '../components/SearchBar.jsx'

const Trade = () => {
  const [users, setUsers] = useState([])
  const [filteredFriends, setFilteredFriends] = useState([])
  const [formChoice, setFormChoice] = useState(null)
  const [tradeName, setTradeName] = useState('')
  const [otherUser, setOtherUser] = useState({
    name: '',
    _id: ''
  })

  const changeSearch = (value) => {
    setOtherUser({ ...otherUser, name:value})
  }

  const changeFriends = (friends) => {
    setFilteredFriends(friends)
  }

  const selectUser = (value) => {
    setOtherUser({name:value.name, _id:value._id})
    setFilteredFriends([])
  }

  async function setupData() {
    //setup
  }

  useFocusEffect(
    React.useCallback(() => {
      setupData();
      return () => {}
    }, [])
  )

  return (
    <>
    <Header back={true}></Header>
    <ScrollView className='flex-1 m-4'>
      <SearchBar data={users} setData={changeFriends} setResult={changeSearch} filter={'name'} limit={5} value={otherUser.name}></SearchBar>
      {Object.entries(filteredFriends).map(([key, value]) => (
        <TouchableWithoutFeedback key={key} onPress={() => selectUser(value)}>
        <View className="flex flex-row">
          <View className="h-10 justify-center items-center flex flex-1 bg-secondary-100/30 border-b-2 border-l-2 border-r-2 border-secondary-100">
            <Text className="text-black text-lg font-psemibold text-center">{value.name}</Text>
          </View>
        </View>
        </TouchableWithoutFeedback>
      ))}
    </ScrollView>
    </>
  )
}

export default Trade

The functionality is straightforward – I would like for users to be able to use the child “Search Bar” component to search and filter through a list of users, and upon selecting one of these users, have it displayed within the “Search Bar” TextInput component. The way I am doing this is by setting the value of both the “Search Bar” TextInput and “SearchBar” component itself to ‘otherUser.name’. This does work, however there is considerable glitching/lagging within the app, particularly when the user is typing fast. I think it might be setting it twice which is causing this issue, but I haven’t found another way do to this.

What is the correct approach I should be using?

Правильно ли я оптимизировал загрузку сайта на html css и js? [closed]

я делаю сайт с использованием большого количества библиотек и он работает довольно быстро, но мне интересно, правильно
ли применять такой подход, и есть ли способы легко его улучшить??

если коротко, то при мопощи JS я отслеживаю загрузку файлов из CDN, и подключаю их по мере необходимости

<script>
    let bootstrapCssLoaded = false;
    let swiperCssLoaded = false;
    let swiperJsLoaded = false;
    let aosCssLoaded = false;
    let aosJsLoaded = false;
    let rellaxJsLoaded = false;
    let lenisJsLoaded = false;
    function checkLoaded(resourсe) {
        switch (resourсe) {
            case "BootstrapAOS":
                if (bootstrapCssLoaded && aosCssLoaded && aosJsLoaded) {
                    document.querySelector('#spinner').style.display = 'none';
                    document.querySelector('#content').style.display = 'block';
                };
                break;
            case "Typed":
                // Инициализация Typed.js

                break;
            case "Swiper":
                if (swiperCssLoaded && swiperJsLoaded) {
                    // Инициализация Swiper

                };
                break;
            case "RellaxLenis":
                if (rellaxJsLoaded && lenisJsLoaded) {

                    // Инициализация Rellax

                    // Инициализация Lenis

                    // Обновление AOS после полной загрузки страницы и инициализации Lenis и Rellax

                };
                break;
        }
    }
</script>
<link id="bootstrap-css" rel="preload" href="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer"
    as="style" onload="this.onload=null;this.rel='stylesheet';bootstrapCssLoaded = true;checkLoaded('BootstrapAOS');">
<noscript>
    <link rel="stylesheet" href="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer">
</noscript>

<link id="aos-css" rel="preload" href="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer" as="style"
    onload="this.onload=null;this.rel='stylesheet';aosCssLoaded = true;checkLoaded('BootstrapAOS');">
<noscript>
    <style>
        #content {
            display: block;
        }

        #spinner {
            display: none;
        }
    </style>
</noscript>

<link id="swiper-css" rel="preload" href="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer" as="style"
    onload="this.onload=null;this.rel='stylesheet';swiperCssLoaded=true;checkLoaded('Swiper');">
<noscript>
    <link rel="stylesheet" href="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer">
</noscript>

<link rel="preload" href="" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript>
    <link rel="stylesheet" href="">
</noscript>

<body> .... </body>
<script src="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
<script src="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
<script src="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer" onload="checkLoaded('Typed')"
    defer></script>
<script src="" onload="lenisJsLoaded=true;checkLoaded('RellaxLenis')" defer></script>
<script src="" integrity="" onload="rellaxJsLoaded=true;checkLoaded('RellaxLenis')" defer></script>
<script id="aos-js" src="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer"
    onload="aosJsLoaded = true;checkLoaded('BootstrapAOS');" defer></script>
<script src="" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer"
    onload="swiperJsLoaded=true;checkLoaded('Swiper');" defer></script>
<script>
    window.onload = () => {
        var videoBackground = document.getElementById('videoBackground');
        var videoElement = document.createElement('video');
        videoElement.autoplay = true;
        videoElement.muted = true;
        videoElement.loop = true;
        var sourceElement = document.createElement('source');
        sourceElement.src = 'video/back.mp4';
        sourceElement.type = 'video/mp4';
        videoElement.appendChild(sourceElement);
        videoBackground.appendChild(videoElement);
        document.querySelector('#spinner').style.display = 'none';
        document.querySelector('#content').style.display = 'block';
        document.querySelector('#yandex-karta').src = 'https://yandex.ru/map-widget/v1/?um=constructor';
    };
</script>

я думаю, должны быть более чистые способы оптимизации, насколько правильно использовать JS в самом начале DOM?

centered flexbox starting from left to right [duplicate]

When I don’t have enough movie covers in the line it looks terrible, for example I needed the cover of the movie “Garfield 2” to start on the left and the next ones inserted to appear on its right.

Application image

This is my source code:

.videos {
  width: 100%;
  margin: 0 !important;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}

.moviecover {
    width: 200px;
    height: 300px;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    border-radius: 10px;
    transition: transform 0.3s ease-in-out;
    margin-top: 5px;
}

<div style="z-index:1;" class="videos">
           <a href="movie.php?id=1">
        <div style="background-image:url(https://media.themoviedb.org/t/p/w300_and_h450_bestv2/9jPHKChBVWfWxXYO1yN4FZF1U2S.jpg);" class="moviecover"></div>
    </a>
    <a href="movue.php?id=3">
        <div style="background-image:url(https://media.themoviedb.org/t/p/w220_and_h330_face/eOSb50gBb4WtbDrMU9yLGKOH9sj.jpg);" class="capafilme"></div>
    </a> <!--- More movies here --></div>

If I do it in other ways, it stops being centered and also ruins the responsiveness on different mobile devices that look great with justify-content: center. I just need it to remain center aligned with the film covers starting from left to right

How to Trigger Event After Semantic UI Search Completes Rendering

I am Hrithik Gupta.

I am working with Semantic UI’s standard search component and I have the following HTML:

<div class="ui search">
  <input class="prompt" type="text" placeholder="Common passwords...">
  <div class="results"></div>
</div>

I want to attach an event to the search input field that triggers only after the search results have been rendered. Currently, the event fires whenever I type a letter (e.g., “P”), but I want it to fire only after the search results have been displayed.

How can I achieve this? Is there a way to detect when the search results are rendered and then trigger my event?

I have tried – change, input event. But they are not working as expected.

I was expecting to find a way to trigger an event only after the search results are displayed, so I can execute additional code or perform actions based on the rendered results.

Firestore – can I query for one doc with parameter other than ID?

I’m coming from MongoDB and I’m struggling to understand getDoc() and getDocs().

Am I understanding this correctly?

Does getDoc() only accept the document’s ID as a parameter? Or can I do a query?

In documentation I can only find code like this:

const docRef = doc(db, "collection", "11aa22bb33ccc");
const myDoc = await getDoc(docRef);

But what if I don’t know the ID or I want to search with a different parameter, such as a field called author? Is it correct that I would not be able to do that with getDoc()?

With MongoDB, I can do db.collection.findOne({ author: "jones" }).

Can I not do that with Firestore?

So if I want to use a query, do I always need to use getDocs()?

If that is the case, I know that I can use limit(1) but handling the response to retrieve that one document feels not-as-smooth-as-mongodb.

I tried this:

const documents = collection(firebaseDb, 'documents');
const query = query(documents, where('author', '==', 'jones'));
const authorDocs = await getDocs(query, limit(1));
console.log(authorDocs[0].data());

And I got an error: Cannot read properties of undefined (reading 'data')

So I think I have to use a forEach, like this:

authorDocs.forEach(doc => console.log( doc.data() ));

But, for only one document? That seems odd. Is there a better way?

What is the most practical way to style a React app in real-world industry applications?

Question for Senior Developers only,

I am seeking advice on the most practical methods to style a React application that are commonly used in real-world, live applications within the industry. With various options available such as CSS Modules, styled-components, plain CSS, and others, I am curious about which approach is preferred and why.

Could you please share your insights on:

  • The most widely used styling methods in modern React applications.
  • The advantages and disadvantages of these methods.
  • Any best practices or tips for managing styles effectively in a large-scale React project.
    Thank you for your time and guidance!

Answers for

  • The most widely used styling methods in modern React applications.
  • The advantages and disadvantages of these methods.
  • Any best practices or tips for managing styles effectively in a large-scale React project.

How can I pass the value between tag to the child component? react jsx

I have jsx like this,

import TableCell from '@mui/material/TableCell';  
import TableCell from '@mui/material/TableRow';

  <TableRow>
  <TableCell sx={{minWidth:45,width:45,maxWidth:45,backgroundColor:"white"}}></TableCell>
  </TableRow>

<TableRow> is from the material ui

Now I want to enhance the TableRow like this,

const EnhancedTableRow= forwardRef((props,ref) => {
  const myDivRef = useRef();
  useImperativeHandle(ref,()=>({
    setReload: () =>{
      setReload(!reload);
    },
    getBoundingClientRect: ()=>{
      return myDivRef.current.getBoundingClientRect();
    },
    isInDiv:(x,y) =>{
      var pos = myDivRef.current.getBoundingClientRect();
      if (x >= pos.x && y >= pos.y && 
       x <= pos.x + pos.width && 
       y <= pos.y + pos.height){
          return true;
      }
      return false;
    }
  }));
  return (<div ref={myDivRef}>
    <TableRow sx={props.sx}>
        ????
      </TableRow>

  </div>)
});

So, when I use EnhancedTableRow instead of TableRow

How can I inheritance the value between tag such as <TableCell sx={{minWidth:45,width:45,maxWidth:45,backgroundColor:"white"}}></TableCell>

to the EnhancedTableRow component?

I want to put this value in ???? in EnhancedTableRow

How do I save a new data to MongoDB?

I’m new to databases and I’m currently working on a Discord bot project. I followed a YouTube tutorial and decided to use MongoDB. However, when I tried to send data for a level system to the database using the save() method, I encountered the following error:

TypeError: level.save is not a function

messageCreate.js:

const { Events, Message } = require("discord.js");
const Level = require("../models/Level");
const getLevelXP = require("../utility/getLevelXP");

function getRandomXP(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);

  return Math.floor(Math.random() * (max - min + 1)) + min;
}

module.exports = {
  name: Events.MessageCreate,
  async execute(message) {
    if (!message.inGuild() || message.author.bot) return;

    const XPToGive = getRandomXP(5, 15);

    const query = {
      userId: message.author.id,
      guildId: message.guild.id,
    };

    try {
      const level = await Level.find(query);
      if (level) {
        level.xp += XPToGive;

        if (level.xp > getLevelXP(level.level)) {
          level.xp = 0;
          level.level += 1;

          message.channel.send(
            `@${message.member} have been leveled up to **Level ${level.level}**`,
          );
        }
        await level.save().catch((error) => {
          console.error(`[ERROR] ${error}`);
          return;
        });
      } else {
        const newLevel = new level({
          userId: message.author.id,
          guildId: message.guild.id,
          xp: XPToGive,
        });

        await newLevel.save();
      }
    } catch (error) {
      console.error(`[ERROR] ${error}`);
    }
  },
};

Level.js:

const { Schema, model } = require("mongoose");

const levelSchema = new Schema({
  userId: {
    type: String,
    required: true,
  },
  guildId: {
    type: String,
    required: true,
  },
  xp: {
    type: Number,
    default: 0,
  },
  level: {
    type: Number,
    default: 0,
  },
});

module.exports = model("Level", levelSchema);

After that error, I double-checked and found that no data had been uploaded to the database. My expectation is to make the data that I’m trying to save, is sent to the database.

how to properly fetch data from medium API in Javascript

I have this medium API Request Data. Medium Docs

Example request:

GET /v1/me HTTP/1.1
Host: api.medium.com
Authorization: Bearer 181d415f34379af07b2c11d144dfbe35d
Content-Type: application/json
Accept: application/json
Accept-Charset: utf-8

In php CODE SAMPLE below, Everything is working fine as I can get my data successfully from Medium API

$url ="https://api.medium.com/v1/me";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization: Bearer 29f812842-xxxxxxxxxxx'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $output = curl_exec($ch);

Here is my Issue. When I tried to fetch the data from javascript it throw error below

XHROPTIONS
https://api.medium.com/v1/me
CORS Missing Allow Origin

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.medium.com/v1/me. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.

below is the code causing the error

async function GetUsersData() {

    try {                
const response = await fetch('https://api.medium.com/v1/me', {
    method: 'GET',
    mode: 'cors',
    credentials: 'include',
    headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer  29f8128xxxx'
  }
});

console.log(response);
alert(response);

} catch (error) {
    // handle the error
alert(error);
} 

}
GetUsersData();

type coersion in JS

Is there any practical difference between Number() and + other than performance or intent?

Tried googling, tried searching for posts from other sites and asked AI but couldn’t find any practical or technical answer.
below code is from AI , in all cases the output is always same. Couldnt find any practical difference.

console.log(“Unary + Operator vs Number Constructor”);

`    

type here

// Conversion of Numeric Strings
let str1 = "42";
console.log("Unary +: ", +str1);         // Output: 42
console.log("Number: ", Number(str1));   // Output: 42

// Conversion of Non-numeric Strings
let str2 = "abc";
console.log("Unary +: ", +str2);         // Output: NaN
console.log("Number: ", Number(str2));   // Output: NaN

// Handling Empty Strings
let str3 = "";
console.log("Unary +: ", +str3);         // Output: 0
console.log("Number: ", Number(str3));   // Output: 0

// Handling Strings with Whitespace
let str4 = "  ";
console.log("Unary +: ", +str4);         // Output: 0
console.log("Number: ", Number(str4));   // Output: 0

// Handling Boolean Strings
let str5 = "true";
console.log("Unary +: ", +str5);         // Output: NaN
console.log("Number: ", Number(str5));   // Output: NaN

// Handling Special Numeric Strings
console.log("Unary + Infinity: ", +"Infinity");       // Output: Infinity
console.log("Unary -Infinity: ", +"-Infinity");       // Output: -Infinity
console.log("Unary NaN: ", +"NaN");                    // Output: NaN

console.log("Number Infinity: ", Number("Infinity"));  // Output: Infinity
console.log("Number -Infinity: ", Number("-Infinity")); // Output: -Infinity
console.log("Number NaN: ", Number("NaN"));            // Output: NaN

// Conversion of Boolean Values
console.log("Unary + true: ", +true);  // Output: 1
console.log("Unary + false: ", +false); // Output: 0

console.log("Number true: ", Number(true));  // Output: 1
console.log("Number false: ", Number(false)); // Output: 0

`