Show and Hide an individual element inside each element of a grid in React

I’m building a game with Phaser and React and I want that whenever the user opens the item menu (a grid with one div per item), if an item is selected, a secondary menu opens only on that div and not on the the rest. But I can’t get it to display only on the div I’m interacting with

BTW. I created a navigation system with the directional keys and some other buttons. When the user presses the “q” button, only one DIV should be selected. I’m using a useState and changing it from false to true every time the Q button is pressed. But this is opening the component on all elements and not only on the selected element :/

enter image description here

This is my code:

const InnerBox = ({
    onDone,
    }) => {

        //handle selector menu
        const [isSelectorOpen, setIsSelectorOpen] = useState(false);

useEffect(() => {
                
                const handleKeyPressed = (e) => {
                        //To close the main menu if the e button is pressed
                        if (['Escape', 'KeyE'].includes(e.code) || e.target.id ==="eButtonX" ) {
                                onDone();
                                new Audio(closeMenu).play()
                        } 
                        //To select all the boxes inside the grid and navigate within the keys
                        let menuElement= document.getElementsByClassName('menu-image')
                        if (!menuElement) return

                        //To iterate in each box inside the grid
                        for(var x=0; x<menuElement.length; x++) {
                                //To open each option in the main menu
                                if (['KeyQ', 'Enter'].includes(e.code) || e.target.id ==="qButtonX") {
                                        //To open the selector option menu inside each individual box
                                        if (menuElement[x].id === "items1") {
                                                new Audio(openSubMenu).play();
                                                setTimeout(() => {
                                                setIsSelectorOpen(true)   
                                                      }, 300);
                                        }
                                        //To keep the border menu item selected even when the button is pressed
                                        return
                                      }
                                menuElement[x].style.border = "solid 3px transparent";
                        }
                }
                
                window.addEventListener('keydown', handleKeyPressed);
                window.addEventListener('pointerdown', handleKeyPressed);
                return () => {
                window.removeEventListener('keydown', handleKeyPressed);
                window.removeEventListener('pointerdown', handleKeyPressed);
                };
        }, [onDone]);

return (
        <>
        <div id="innerMenuBar" style={{ position:'fixed', border: 'none', padding: 20, background:'#4c75fb', boxShadow: '0 5px 0 0 #24397D', borderRadius:5, outlineStyle:'none', left:'50%', top:'50%', transform: "translate(-50%, -50%)", zIndex:'2', marginBottom:'0', height:'70vh' }}>

            <div id='innerMenu' className='menu-grid' style={{ overflow:'hidden', overflowY:'scroll', paddingRight:'10px' }}>

                <div className="menu-item" style={{ border: 'solid 1px', position: 'relative'}}>

                        <img id="items1" className="menu-image" src={items} style={{ border: 'solid 3px'}}
                            onPointerOver={e => {
                                    e.currentTarget.src = items2
                                    e.target.style.border="solid 3px"
                                    new Audio(moveMenu).play();} 
                                    
                            } 
                            onPointerLeave={e => {
                                    e.currentTarget.src = items
                                    e.target.style.border="solid transparent 3px"}
                            }
                            /> 
                            { isSelectorOpen ? <Selector /> : null }
                </div>

                <div className="menu-item" style={{ border: 'solid 1px', position: 'relative'}}>

                        <img id="items2" className="menu-image" src={items} style={{ border: 'solid transparent 3px'}}
                            onPointerOver={e => {
                                    e.currentTarget.src = items2
                                    e.target.style.border="solid 3px"
                                    new Audio(moveMenu).play();} 
                                    
                            } 
                            onPointerLeave={e => {
                                    e.currentTarget.src = items
                                    e.target.style.border="solid transparent 3px"}
                            }
                            
                            /> 
                            { isSelectorOpen ? <Selector /> : null }
                </div>
            </div>

            <div className='innerMenu-description'>
                <p> Description: Lorem Ipsu Lorem Ipsu</p>
            </div>

        </div>
</>
    );
};

export default InnerBox;

facing some issue to set type on sweetalert2

Typescript gave me 2 errors in the toastMixin variable and into the animation object. I didn’t find any solution to solve it.

Error:

let toastMixin: typeof Swal
No overload matches this call.
  Overload 1 of 2, '(options: SweetAlertOptions<any, any>): Promise<SweetAlertResult<any>>', gave the following error.
    Argument of type '{ animation: boolean; title: string; }' is not assignable to parameter of type 'SweetAlertOptions<any, any>'.
      Object literal may only specify known properties, and 'animation' does not exist in type 'SweetAlertOptions<any, any>'.
  Overload 2 of 2, '(title?: string | undefined, html?: string | undefined, icon?: SweetAlertIcon | undefined): Promise<SweetAlertResult<any>>', gave the following error.
    Argument of type '{ animation: boolean; title: string; }' is not assignable to parameter of type 'string'.ts(2769)

Code: TS showing the error on let toastMixin and in animation object

 export const errorHandle = (massage:string) => {
    let toastMixin = Swal.mixin({
        toast: true,
        icon: 'success',
        title: 'General Title',
        animation: false,
        position: 'top-right',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer)
            toast.addEventListener('mouseleave', Swal.resumeTimer)
        }
    });

    if (massage === 'added') {
        toastMixin.fire({
            animation: true,
            title: 'Successfully added'
        });
    } else if (massage === 'duplicate') {
        toastMixin.fire({
            title: 'You already added the developer',
            icon: 'error'
        });
    } else if (massage === 'removed') {
        toastMixin.fire({
            animation: true,
            title: 'Removed'
        });
    }
}

how to disable some dates in react-calendar

Could someone tell me how to pass an array of disabled dates to the calendar?

I searched but couldn’t find how to do it

https://www.npmjs.com/package/react-calendar

import React, { useState, useEffect} from 'react';
import Api from '../../services/api';
import Calendar from 'react-calendar';
import { useParams } from "react-router-dom";
import 'react-calendar/dist/Calendar.css';

function MyApp() {
  const { id } = useParams();
  const [value, onChange] = useState(new Date());
  const [disabledDates, setDisabledDates] = useState([]);

  useEffect(() => {
    loadDisabledDates();
  }, []);

  function loadDisabledDates()
  {
    Api
      .get("/dates/"+id)
      .then((response) => {
        setDisabledDates(response.data);
      })
      .catch((err) => {
        console.error("error: " + err);
      });
  }

  return (
    <div>
      <Calendar onChange={onChange} value={value} />
    </div>
  );
}

How to use Ajax in pagination with php

I have this pagination written in php that works fine, but I want to use ajax to implement this so that the pages won’t have to reload every time a link is clicked. I have gone through previous questions asked on this same topic here on SO and other blogs but I’m not getting it right.
Here’s my pagination code in nav_tbl.php

                        if(!empty($_POST['rownum'])){
                            $rowno = $_POST['rownum'];
                            //get current page
                            $currentpage = isset($_POST['currentpage']) ? $_POST['currentpage'] : 1;
                            $no_of_records_per_page = $rowno;
                            $setoff = ($currentpage - 1) * $no_of_records_per_page;

                            //get total number of records in database
                            $sqlcount = "SELECT *FROM evatbl WHERE RegNo = ?";
                            $stmt = $con->prepare($sqlcount);
                            $stmt->bind_param("s", $pregno);
                            $pregno = $_SESSION['regno'];
                            $stmt->execute();
                            $result = $stmt->get_result();
                            $num_rows = $result->num_rows;
                            $totalpages = ceil($num_rows/$no_of_records_per_page);
                            
                            //query for pagination
                            $sqllimit = "SELECT *FROM evatbl WHERE RegNo = ? ORDER BY CourseTitle LIMIT $setoff, $no_of_records_per_page";
                            if ($stmt = $con->prepare($sqllimit))
                            {
                                $stmt = $con->prepare($sqllimit);
                                $stmt->bind_param("s", $pregno);
                                $pregno = $_SESSION['regno'];
                                $stmt->execute();
                                $result = $stmt->get_result();
                                $num_rows = $result->num_rows;
                                if ($num_rows>0)
                                {
                                    $count = 1;
                                    echo "<table id='t01' class='table' width='100%'>
                                    <tr id='tblhead'>
                                    <th>SN</th>
                                    <th>Course Title</th>
                                    <th>Course Code</th>
                                    <th>Credit Unit</th>
                                    <th>Course Lecturer</th>
                                    <th>Rating(%)</th>
                                    </tr>";
                                    while($row = $result->fetch_assoc())
                                    {
                                        $ccode = $row['CourseCode'];
                                        $ctitle = $row['CourseTitle'];
                                        $cunit = $row['CreditUnit'];
                                        $clec = $row['CourseLecturer'];
                                        $crate = $row['Rating'];
                                        echo "
                                        <tr>
                                        <td>$count</td>
                                        <td>$ctitle</td>
                                        <td>$ccode</td>
                                        <td>$cunit</td>
                                        <td>$clec</td>
                                        <td>$crate</td>
                                        </tr>";
                                        $count++;
                                    }
                                    echo "</table>";
                                }
                                else{
                                    echo "<p style='color:darkred;margin-bottom:0;'>Oops! No records found.</p>";
                                }
                                    ?><br>
                            <div class="nav_div" id="nav_div">
                            <label for="navno">Navigate pages: </label>    
                                <?php
                            //First Page Button
                            if($currentpage > 1)
                            {
                                echo "<a class='nav_a' id='first' href='view_eva.php?limit=".$rowno."&currentpage=".(1)."' title='First'><<</a>";
                            }
                            //Previous Page Button
                            if($currentpage >= 2)
                            {
                                echo "<a class='nav_a' id='prev' href='view_eva.php?limit=".$rowno."&currentpage=".($currentpage - 1)."' title='Previous'><</a>";
                            }
                            ?>
                            <select class='navno' name='navno' id='navno' onchange="pageNav(this)">
                            <?php
                            //Link to available number of pages with select drop-down
                                for($i = 1; $i <= $totalpages; $i++)
                                {
                                    echo "<option class='bold'";
                                    if ($currentpage==$i) 
                                    { 
                                        echo "selected"; 
                                    } 
                                    echo " value='view_eva.php?limit=".$rowno."&currentpage=".$i."'>".$i."</option>";
                                }
                            ?>
                            </select>
                            
                            <?php
                            //Next Page Button
                            if($currentpage < $totalpages)
                            {
                                echo "<a class='nav_a' id='next' href='view_eva.php?limit=".$rowno."&currentpage=".($currentpage + 1)."' title='Next'>></a>";
                            }
                            //Last Page Button
                            if($currentpage <= $totalpages - 1)
                            {
                                echo "<a class='nav_a' id='last' href='view_eva.php?limit=".$rowno."&currentpage=".($currentpage = $totalpages)."' title='Last'>>></a>";
                            }
                            ?>                        
                            </div>
                        <?php
                        }
                        else
                        {
                        echo "<p style='color:darkred;margin-bottom:0;'>Oops! No records found.</p>";
                        }
                            ?>

And here’s the Ajax code to set number of rows to display per page using a select dropdown option

$(document).on('change', '#rowno', function(e){ 
    e.preventDefault();
    var rownum = $('#rowno').val();
        if($('#check').is(":checked")) {
            $('#check').prop('checked',false);
        }
        $.ajax({
        type: 'POST',
        url: 'navtbl.php',
        cache: false,
        async: false,
        data: {
            rownum : rownum
        },
        success: function(datalog){
            console.log(datalog);
            $("#display_table").html(datalog).show();
        },
        error: function(datalog){
            swal("Oops.", "An error occured! Unable to fetch result.", "error");
        }
    });
});
// Call Function to load and display table on Page Load
function Ini_loadTable(){
    var rownum = $('#rowno').val();
        $.ajax({
        type: 'POST',
        url: 'navtbl.php',
        cache: false,
        async: false,
        data: {
            rownum : rownum
        },
        success: function(datalog){
            console.log(datalog);
            $("#display_table").html(datalog).show();
        },
        error: function(datalog){
            swal("Oops.", "An error occured! Unable to fetch result.", "error");
        }
    });
}

Please, any help will be much appreciated. Thank you.

Having trouble creating an element using a button [duplicate]

I am having trouble creating an element using a button, I look for other threads with a similar case but could not find anything that could help me.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CustBookMarkTesting</title>
    <!--bootstrap-->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" >
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" ></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
    <script>

    </script>
</head>


<body>
    <button name="CustButton" onclick="CreateNewDom()">create a button?</button>
</form>

<script>
    function CreateNewDom() {
        var DOMHeadingOne = document.createElement("button");
        DOMHeadingOne.setAttribute("role = 'btn btn-danger'", "text");
        DOMHeadingOne.classList.add("CustButton");
        document.getElementById("editor").appendChild(DOMHeadingOne);
    }
</script>
    
</body>
</html>

This is my code, I am trying to make a custom bookmark with bootstrap. When I load it up to my browser, it creates a very small button and when clicked it reloads the tab. My goal, for now, is to make a button that links to anything(website, image, message, etc) I am a beginner at all things programming so please be as clear as possible.

I tried to change a lot of the constraints to find which ones affected the function, I couldn’t find which ones did what. Would be grateful if someone responds to this post to help me tackle this obstacle.

Thanks

  • Dick Long

charts.js data doesn’t fit second y-axis

I have a simple element, containing whole dataset.
Subset “change” is meant for second Y-Axis but using the code below, the “change” dataset still displays in relation to left axis.
Please advise, documentation is not very clear on this topic. I would expect the blue line to be in relation to the right axis, using below code.

  let chartElement = $('#mainChart');
  const data = chartElement.data('chart-dataset');
  const cfg = {
      type: 'line',
      data: {
          datasets: [{
              'label': 'Total balance',
              data: data.stats,
              parsing: {
                  xAxisKey: 'time',
                  yAxisKey: 'total',
                  yAxisID: 'y',
              },
              backgroundColor: 'rgb(98,250,2)',
              borderColor: 'rgb(98,250,2)',
          }, {
              'label': 'Risk balance',
              data: data.stats,
              parsing: {
                  xAxisKey: 'time',
                  yAxisKey: 'risk',
                  yAxisID: 'y',
              },
              backgroundColor: 'rgb(255,191,34)',
              borderColor: 'rgb(255,191,34)',
          }, {
              'label': 'Average risk',
              data: data.stats,
              parsing: {
                  xAxisKey: 'time',
                  yAxisKey: 'avRisk',
                  yAxisID: 'y',
              },
              backgroundColor: 'rgb(236,4,4)',
              borderColor: 'rgb(236,4,4)',
          }, {
              'label': 'Change %',
              data: data.change,
              parsing: {
                  xAxisKey: 'time',
                  yAxisKey: 'change',
                  yAxisID: 'yPercent',
              },
              backgroundColor: 'rgb(31,116,241)',
              borderColor: 'rgb(31,116,241)',
          }]
      },
      options: {
          scales: {
              y: {
                  id: 'y',
                  type: 'linear',
                  position: 'left',
                  ticks: {
                      beginAtZero: true,
                  }
              },
              yPercent: {
                  id: 'yPercent',
                  type: 'linear',
                  position: 'right',
                  suggestedMax: 1.0,
                  suggestedMin: -1.0,
                  ticks: {
                      precision: 4,
                  }
              },
          }
      }
  }
  const mainChart = new Chart(
      chartElement,
      cfg
  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="mainChart" data-chart-dataset="{&quot;stats&quot;:[{&quot;time&quot;:&quot;2022-03-27 00:00:05&quot;,&quot;total&quot;:424.97014172,&quot;risk&quot;:307.70675152,&quot;avRisk&quot;:34.18963905777778},{&quot;time&quot;:&quot;2022-03-27 00:30:06&quot;,&quot;total&quot;:424.97666652,&quot;risk&quot;:307.70675152,&quot;avRisk&quot;:34.18963905777778},{&quot;time&quot;:&quot;2022-03-27 01:00:06&quot;,&quot;total&quot;:425.22301931,&quot;risk&quot;:307.70675152,&quot;avRisk&quot;:34.18963905777778},{&quot;time&quot;:&quot;2022-03-27 01:30:06&quot;,&quot;total&quot;:424.91940821,&quot;risk&quot;:307.70675151999995,&quot;avRisk&quot;:34.189639057777775}],&quot;change&quot;:[{&quot;time&quot;:&quot;2022-03-27 00:00:05&quot;,&quot;change&quot;:0},{&quot;time&quot;:&quot;2022-03-27 00:30:06&quot;,&quot;change&quot;:0.0015353549248324776},{&quot;time&quot;:&quot;2022-03-27 01:00:06&quot;,&quot;change&quot;:0.05796854495972885},{&quot;time&quot;:&quot;2022-03-27 01:30:06&quot;,&quot;change&quot;:-0.07140043840822045}]}" width="1639" height="819" style="display: block; box-sizing: border-box; height: 819px; width: 1639px;"></canvas>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>

Nodejs – How to get key by value when value is an array? [duplicate]

I have seen other posts about how to get the key by value by doing something like this:

myObj {
  key1: "value1",
  key2: "value2"
}

return Object.keys(myObj).find(key => object[key] === value);

But how about a scenario where the value is an array? Something like this:

myObj {
  key1: [ "value1", "value3", "value4" ],
  key2: "value2"
}

return Object.keys(myObj).find(key => object[key] === value);

So if my value is value4, I want to still be able to return key1. If I pass the array position like this it works, but that kind of defeats the purpose:

return Object.keys(myObj).find(key => object[key][2] === value);

Any ideas? TIA

How to identify which dependencies use eval

I am trying to make a chrome extension but I get an error saying I can’t use eval. My code doesn’t contain eval so it has to be in one of my dependencies. What’s a quick and easy way to see which dependency or sub-dependency is using eval? I removed node_modules from the search exclude on VSCode, and I got over 100 results, but it’s still unclear which dependency has it because it is under some sub-dependency folders.

How i can filter array by another array if 1 of elements equal?

My array for filter:

types: [
  { type: 0, name: 'Item_1' },
  { type: 1, name: 'Item_2' },
  { type: 2, name: 'Item_3' },
  { type: 3, name: 'Item_4' },
  { type: 4, name: 'Item_5' },
  { type: 5, name: 'Item_6' },
  { type: 6, name: 'Item_7' },
]

filterBy:

sort: [1, 2, 3];

How i can do smth like this but for multiple values?

    filterType(item) {
        return item.type.toString() == this.sort;
    }

Stripe – ERROR: elements should be an Elements group. You specified: object

I have a problem while creating a setup for card payment.

  const result = await stripe.confirmPayment({
    elements,
    confirmParams: {
      return_url: 'https://example.com/order/123/complete',
    },
  });

But receiving an error when submitting:

IntegrationError: Invalid value for stripe.confirmPayment(): elements should be an 
Elements group. You specified: object.

I dont know why does it happen because I follow the tutorial steps: https://stripe.com/docs/payments/save-and-reuse?platform=web&html-or-react=react#web-submit-payment-details

Playground with the problem: https://codesandbox.io/s/react-stripe-js-forked-wwydkc?file=/src/components/demos/CardForm.js:1073-1245

How to reproduce? Just type in the card input: 4242 4242 4242 4244 and some random valid date and click PAY.

Socketio showing: polling-xhr.js:203 POST https://tannax.com/socket.io/?EIO=4&transport=polling&t=N_DgMGp&sid=tN5At8vMOxNJ7OWBAAC9 400

I am building a simple chat interface on my web application using Flask Socketio module. The chat interface works very well on my development platform but it doesn’t work when I moved the entire flask web application to my domain hosted in a virtual private server. The understated error keeps popping up on console:

“polling-xhr.js:203 POST https://tannax.com/socket.io/EIO=4&transport=polling&t=N_DgMGp&sid=tN5At8vMOxNJ7OWBAAC9 400″

see my client side code below:

document.addEventListener(‘DOMContentLoaded’, () =>{
var socket = io.connect(‘https://’ + document.domain + ‘:’ + location.port);

    socket.on('message', data => {
        const p = document.createElement('p');

        const span_username = document.createElement('span');
        const span_timestamp = document.createElement('span')
        const br = document.createElement('br');
        span_username.innerHTML = data.username
        span_timestamp.innerHTML = data.time_stamp;

        p.innerHTML = br.outerHTML + data.msg + br.outerHTML ;
        document.querySelector('#display-message-section').append(p);
        let messageBody = document.querySelector('#display-message-section');
        messageBody.scrollTop = messageBody.scrollHeight;

    });

Please someone should assist me.

{$match{ field: $in: [OID ARRAY]}} aggregate is not working at ts-mongoose

I am using ts-mongoose.
It implements something in the form of SNS.

I’m creating an aggregate query to retrieve only what my followers have written, and I don’t think this will work as I intended.

What am I doing wrong?

code :

const posts = await this.posts.aggregate([
{ $match: { 'uploader': { $in: followers } } }
<another aggregate>
}

mongoose debug log :

posts.aggregate([ { '$match': { uploader: { '$in': [ new ObjectId("6239747c4658ebecd4a242cd"), new ObjectId("623967204658ebecd4a2402d") ] } } }, { '$sort': { createdAt: -1 } }, { '$limit': 8 }, ...<another log...>

scheme of post model:

const postsSchema = createSchema(
  {
    contents: Type.string(),
    uploader: Type.objectId(),
    hashtags: Type.array().of(Type.string()),
  },
  { versionKey: false, timestamps: true },
);

How to screen capture a entire webpage and also get its dimansions

please I am working on a project in which a major requirement is a feature annotate different parts of a webpage as illustrated below.

Feature I am trying to implement

To implement this, I came up with this approach:

  • First, when a user clicks on “Add point”, the mouse coordinates are stored in a database, along with the widow’s dimensions (width and height). (NOTE: the default right-click action is overridden by displaying an “Add point” button)

  • Next, if a screenshot of the webpage in those dimensions doesn’t exist, I want to take a FULL screenshot (including elements out of scrollview) of the webpage in that dimension and store in the database.

  • Finally, in my admin system I want to display the screenshots with “point” elements overlayed on top of it (based on the saved mouse positions).

Kindly assist by showing how to take full screenshots and taking dimensions.

P.S:. If you have an approach that works better, please let me know.

Why do I have to refresh my Express endpoint when trying to grab req.headers.cookies from frontend

I am running into a problem where I have to refresh my express endpoint to be able to read req.headers.cookie If I do not refresh the endpoint then console.log(req.headers.cookie) returns undefined instead of the assigned value. I have included some photos below to better show you what my problem is I have also included my back-end code that sets the cookie and should also console.log(req.headers.cookie) Thanks in advance for any help!

Images:

First time I hit the Login button this is the cookie I get.
First Login Attempt

First Response

Seconed time I hit the login button this is the cookie I get.
Seconded Login Attempt

Notice below on our second back-end response how the AccessToken value is equal to the first response we received on our front-end. Almost as if our backend code is always reading the previous value of req.headers.cookie instead of the current value.
Seconded Response

Back-End Code:

app.get('/', (req, res) => {

try {
    res.cookie("AccessToken", globalToken, {
        sameSite: 'strict',
        maxAge: ((((1000 * 60) * 60) * 24) * 7), /* expire a week from today */
        httpOnly: true,
        path: '/'
        // secure: true
    });

    res.send();

} catch (error) {
    console.log(error)
} finally {
    console.log(req.headers.cookie);
    frontendCookie = req.headers.cookie;
}

});