Uncaught TypeError: Cannot read properties of undefined (reading ‘logopath’)

Can someone please help me with understanding what is wrong with my code here?

I keep getting an uncaught TypeError regarding my logoPath, but it is defined correctly. The page is www.eastvanbaseball.com/standings.

Uncaught TypeError: Cannot read properties of undefined (reading ‘logopath’)

This is a function that takes JSON data and computes standings. There is a bunch of additional logic after what I have shared, I can update with that if helpful, but I assume what i shared is where the issue lays. Thank you!

Below is my code:

<div class="selectGroupWrapper">
    <div class="selectGroupList">
        <select id="selectStandingsYear" onchange="getStandings()">
            <option value="2023" selected>2023</option>
            <option value="2022">2022</option>
            <option value="2021">2021</option>
            <option value="2019">2019</option>
            <option value="2018">2018</option>
            <option value="2017">2017</option>
        </select>
    </div>
</div>

<div id="standings_table"></div>
<div id="ringers_table"></div>

<script>
    $(document).ready(function(){
      $("select").trigger('change');
    });

     var teamDb = [
        { fullName: "Chinatown Cobras", lastName: "Cobras", abbr: "CHN", logoPath: "Cobras.png", participating: [true, true, true, false, true, true, true] },
        { fullName: "Clark Park Brawlers", lastName: "Brawlers", abbr: "CP", logoPath: "Brawlers-2019.png", participating: [true, true, true, false, false, true] },
        { fullName: "East Van Black Sox", lastName: "Black Sox", abbr: "SOX", logoPath: "Black_Sox.png", participating: [true, true, true, false, true, true, true] },
        { fullName: "Blood Alley Butchers", lastName: "Butchers", abbr: "BAB", logoPath: "butchers_2.png", participating: [false, false, false, false, false, false, false] },
        { fullName: "Gastown Gaolers", lastName: "Gaolers", abbr: "GAS", logoPath: "Gaolers.png", participating: [true, true, true, false, true, true, false] },
        { fullName: "Mt Pleasant Murder", lastName: "Murder", abbr: "MT", logoPath: "Murder.png", participating: [true, true, true, false, false, true, true] },
        { fullName: "Railtown Spikers", lastName: "Spikers", abbr: "RT", logoPath: "Spikers_alt.png", participating: [true, true, true, false, true, true, true] },
        { fullName: "Strathcona Stevedores", lastName: "Stevedores", abbr: "STR", logoPath: "Stevedores.png", participating: [true, true, true, false, false, true, true] },
        { fullName: "Sunrise Cosmos", lastName: "Cosmos", abbr: "COS", logoPath: "cosmos.png", participating: [true, true, true, false, true, true, true] },
        { fullName: "Sunset Stilettos", lastName: "Stilettos", abbr: "SET", logoPath: "Stilettos.png", participating: [true, true, true, false, false, true, true] },
        { fullName: "Vancouver Isotopes", lastName: "Isotopes", abbr: "VAN", logoPath: "isotopes.png", participating: [true, true, true, false, false, false, false] },
        { fullName: "Little Mountain Blasters", lastName: "Blasters", abbr: "LM", logoPath: "blasters.png", participating: [false, false, true, false, true, true, true] },
        { fullName: "Brewery Creek Mashers", lastName: "Mashers", abbr: "BC", logoPath: "mashers.png", participating: [false, false, false, false, true, true, true] },
        { fullName: "EVBL Ringers", lastName:"Ringers", abbr:"RNG", logoPath:"ev.png", participating: [false, false, false, false, false, true, false] }];

   var yearToFilePath = {
        "2023": "assets/schedule/evbl_schedule_2023.json",
        "2022": "assets/schedule/evbl_schedule_2022.json",
        "2021": "assets/schedule/evbl_schedule_2021.json",
        "2019": "assets/schedule/evbl_schedule_2019.json",
        "2018": "assets/schedule/evbl_schedule_2018.json",
        "2017": "assets/schedule/evbl_schedule_2017.json"
    };

   var logoRootURL = "/assets/team_logos/";
   var ringerNameData = {fullName:"EVBL Ringers",lastName:"Ringers",abbr:"RNG",logoPath:"ev.png"};
   var tieCheck, numTies, c;
   var useLogos = true;
   var tableContent, ringerTableContent;
   
   function getStandings() {

        var visTeam, visAbbr, visLogo, visScore, homeTeam, homeAbbr, homeLogo, homeScore;
        var teamNameData = [],
            teamRecords = [],
            teamSort = [],
            obj,
            getYear = document.getElementById("selectStandingsYear").value,
            season = getYear - 2017,
            teamSeasonIndex = 0;
      for (let i = 0; i < teamDb.length; i++) {
    console.log("Team Object:", teamDb[i]);
    if (teamDb[i].participating[season]) {
        obj = teamDb[i];
        if (Array.isArray(teamDb[i].logoPath)) { // Check if logoPath is an array
            console.log("Logo Path Array:", teamDb[i].logoPath);
            for (let j = 0; j < teamDb[i].logoPath.length; j++) {
                if (parseInt(teamDb[i].logoPath[j].yearStart) <= getYear) {
                    obj.logoPath = teamDb[i].logoPath[j].useLogo;
                }
            }
        } else { // Handle the case where logoPath is not an array
            obj.logoPath = teamDb[i].logoPath; // Assign logoPath directly
        }
        console.log("Modified Team Object:", obj);
        obj.index = teamSeasonIndex;
        teamNameData[teamDb[i].abbr] = obj;
        teamSeasonIndex++;
        obj = {
            team: teamDb[i].abbr,
            gp: 0,
            w: 0,
            l: 0,
            t: 0,
            rs: 0,
            ra: 0,
            strkW: 0,
            strkL: 0,
            strkUnb: 0,
            strkWnl: 0,
            lastFive: '',
            lastW: 0,
            lastL: 0,
            lastT: 0,
            rng_gp: 0,
            rng_w: 0,
            rng_l: 0,
            rng_t: 0,
            rng_rdiff: 0
        };
        teamRecords.push(obj);
        obj = {
            pct: 0,
            p_pct: 0.5,
            runDiff: 0,
            rngwpct: 0.5,
            totRunDiff: 0,
            w_l: 0
        };
        teamSort.push(obj);
    }
}

How to do this I am not a pro develper [closed]

Hello there I got an query

I didn’t that there are my

Here are many this I trasdsd ;lkjsd and ther

Please do a final review of your question and then post.
Please do a final review of your question and then post.Please do a final review of your question and then post.Please do a final review of your question and then post.Please do a final review of your question and then post.Please do a final review of your question and then post.Please do a final review of your question and then post.Please do a final review of your question and then post.v

Clicking the current audio button doesn’t pause the previous audio that was already being played

import React, { useState, useRef } from 'react';
const PlayAudio = ({ content }) => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [previous, setPrevious] = useState({})
    const audioRef = useRef(null);
    const previousRef = useRef(null);


    const togglePlay = () => {
        previousRef.current = audioRef.current;
        if (!isPlaying) {
            previousRef.current.pause();
            audioRef.current.play();
        } else {
            audioRef.current.pause();
        }
        setIsPlaying(!isPlaying);
    };


    return (
        <div>
            {content.audio && (
                <audio ref={audioRef} src={content.audio}></audio>
            )}
            {content.audio && (
                <img
                    src="play.svg"
                    alt=""
                    onClick={togglePlay}
                    className="cursor-pointer"
                />
            )}
        </div>
    );
};

export default PlayAudio;

Clicking the audioRef doesn’t pause the previous audio that is being played on the website.

I tried doing some tweaks but none of them works! How to achieve that functionality?
Any Idea?

Using Constant while calling a function in a conditional

I am trying to get the end users location and if they are within a service area (poly) let them know. I have managed to get everything functional except the conditional for the output.

I am grabbing geolocation with the following:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
  });
} else {
  console.log("Geolocation is not supported by this browser.");
}

My poly detection is:

polygone=   [
    [43.163834,-84.134153],
    [43.163834,-83.420042],
]

function isPointInPoly(point, vs) {
    var x = point[0], y = point[1];
    var inside = false;
    for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
        var xi = vs[i][0], yi = vs[i][1];
        var xj = vs[j][0], yj = vs[j][1];
        var intersect = ((yi > y) != (yj > y))
            && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
    }

    return inside;
};

What I have tried:

if(isPointInPoly([ $latitude, $longitude ], polygone) === true) {
    $("#output").html('Yup');
} else {
    $("#output").html('Nope');
}

I’m not sure if I’m going about this correctly, but I have looked up ‘using const in conditionals’ and a few other term, to no avail.

I set up a fiddle here as well.

In the end I would just like to show a message to users in the area, and another to users outside the area.

unable to get the results on spreadsheet despite running a code and it saying execution completed

Hi guys I am a total noob please if sombody can help

I have a live portfolio in my spread sheet so IN Cell E32 the % change in portfolio gets updated on real time basis, now I want to get the % change every day so I copied a code

I went to my google sheet, clicked on extension and then on add script

Now there I pasted my code and clicked on run, I did this some 10 times but nothing is happening on my google sheet, can somebody please help,

I also dont know how many times I might have run the code so I need help in deleting all these codes executing as well

the code is as follows
enter image description here

also if sombody can explain me, once this code runs how do I run another code because every time I open this add script I can se the old code only, dont know how to add a new one

I have explained everything above

Populating element with thousands of data, freezes the webpage. How do I fix this?

homepage/index.php

var form = document.createElement("form");
form.id = "survey-form";
var elements = [
       {
           type: "select",
           label: "Send to employee",
           id: "empno",
           options: [] // Options will be populated dynamically
       },
];
elements.forEach(function (element) {
       var wrapper;
       var label = document.createElement("label");
       label.className = "form-label";
       label.textContent = element.label;
       if (element.type === "select") {
           input = document.createElement("select");
           input.id = element.id;
           input.className = "user-input";

           form.appendChild(label);
           form.appendChild(input);
           fetchOptionsUsingWorker(input, element.options);

           $(document).ready(function() {
               $('#' + element.id).select2();
           });
       }
});

function fetchOptionsUsingWorker(selectElement) {
    var worker = new Worker('optionsWorker.js');

    worker.addEventListener('message', function(e) {
        if (e.data.type === 'optionsData') {
            var optionsData = e.data.data;
            populateSelectWithOptions(selectElement, optionsData);
        } else if (e.data.type === 'error') {
            console.error('Error fetching options data:', e.data.message);
        }
    });

    worker.postMessage('fetchOptions');
}

function populateSelectWithOptions(selectElement, optionsData) {
    selectElement.innerHTML = '';
    optionsData.forEach(function (option) {
        var optionElement = document.createElement("option");
        optionElement.value = option;
        optionElement.text = option;
        selectElement.appendChild(optionElement);
     });
}

homepage/optionsWorker.js

function fetchOptionsFromServer() {
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "../backend.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onload = function () {
            if (xhr.status === 200) {
                var data;
                if (xhr.responseText === "No data found") {
                    data = ["No data found"];
                } else {
                    data = JSON.parse(xhr.responseText);
                }
                resolve(data);
            } else {
                reject(xhr.statusText);
            }
        };
        var data = "input=get_options";
        xhr.send(data);
    });
}

self.addEventListener('message', async function(e) {
    if (e.data === 'fetchOptions') {
        try {
            const optionsData = await fetchOptionsFromServer();
            self.postMessage({ type: 'optionsData', data: optionsData });
        } catch (error) {
            self.postMessage({ type: 'error', message: error });
        }
    }
});

As there are thousands of data being fetched from the server, I used webworkers to run the code which fetches the data in the background thread, otherwise the webpage keeps on freezing. But even after using webworkers, it was of no good, as the webpage still freezes. Where am I going wrong? Please guide me.

HTML borders for dynamic data

I have a below data, I’m expecting to generate a border dynamically for each data set,


<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Subject</th>
      <th>Average Marks</th>
      <th>Name</th>
      <th>Marks Scored</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Maths</td>
      <td>80</td>
      <td>Student 1</td>
      <td>90</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Maths</td>
      <td>80</td>
      <td>Student 2</td>
      <td>70</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Maths</td>
      <td>80</td>
      <td>Student 3</td>
      <td>80</td>
    </tr>
    <tr>
      <th>3</th>
      <td>English</td>
      <td>80</td>
      <td>Student 1</td>
      <td>90</td>
    </tr>
    <tr>
      <th>4</th>
      <td>English</td>
      <td>80</td>
      <td>Student 2</td>
      <td>70</td>
    </tr>
  </tbody>
</table>

Actual table,

enter image description here

Expectation,

enter image description here

Any suggestion would be appreticiated

Coding a WooCommerce Multi-Step Checkout

I’ve been trying to get some code to work but doesn’t seem to be firing. Think I might be missing something between versions.

I’m using the base checkout from WooCommerce plugin. Text appears at the bottom of checkout instead of buttons, but that might be a theme issue and haven’t added a CSS. Pretty sure I’ve enqueued the script right from everything I can find.

Here’s what I have:

In Function.php

add_action( 'woocommerce_after_checkout_form', 'step_controls');
function step_controls() {
    echo '
        <div class="step_controls_container">
            <a class="btn-primary step_back_to_cart" href="'.site_url("/cart", "https").'">Back to Cart</a>
            <a class="btn-primary step_next">Next</a>
            <a class="btn-primary step_prev">Previous</a>
        </div>
    ';
}
//

function cart_steps() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('cartsteps', get_stylesheet_directory_uri() . '/js/cart-steps.js');

} 
add_action( 'wp_enqueue_scripts', 'cart_steps' ); 

In custom JS file

var steps = [
    {
        name: 'Billing & Shipping Details',
        selector: '#customer_details'
    },
    {
        name: 'Order Review & Payment',
        selector: '#order_review'
    }
]
var activeStep;
// Adjust the array length to match zero-base
var stepsLengthAdjusted = steps.length - 1;

// Utility functions
function initSteps() {
    // Set first checkout step
    sessionStorage.setItem('checkout_step', '0');
}
function getCurrentStep() {
    return sessionStorage.getItem('checkout_step');
}
function showCurrentStep() {
    activeStep = getCurrentStep();
    // Loop through the steps and see which is currently active
    for (let i = 0; i < steps.length; i++){
        let stepSelector = steps[i].selector;
        if ( i != activeStep ) {
            // Hide if not the current step
            $(stepSelector).hide();
        } else {
            // Show the correct step div
            $(stepSelector).fadeIn();
            // Show or hide navigation  buttons as appropriate
            $('.step_next, .step_prev').show();
            if ( getCurrentStep() == stepsLengthAdjusted ) {
                // This is the last step, so remove next button
                $('.step_next').hide();
            }
            if ( getCurrentStep() == 0 ) {
                // This is the first step, so remove previous button
                $('.step_prev').hide();
            }
        }
    }
    // Always go to the top of the steps
    $("body").get(0).scrollIntoView();
}
function nextStep() {
    if ( getCurrentStep() < stepsLengthAdjusted ) {
        var nextStep = parseInt(getCurrentStep()) + 1;
        sessionStorage.setItem('checkout_step', nextStep);
        showCurrentStep();
    }
}
function previousStep() {
    if ( getCurrentStep() > 0 ) {
        var previousStep = parseInt(getCurrentStep()) - 1;
        sessionStorage.setItem('checkout_step', previousStep);
        showCurrentStep();
    }
}

// Initialise
if ( getCurrentStep() == null ) {
    initSteps();
}
// Always show the correct step
showCurrentStep();
// Navigation
$('.step_next').click(function() {
    nextStep();
});
$('.step_prev').click(function() {
    previousStep();
});
// Hide a elements not in parent containers!
$('h3#order_review_heading').hide();

// Flush the current step when navigating away from checkout to prevent customer confusion
if ( !$('body').hasClass('woocommerce-checkout') ) {
    initSteps();
}

$('body').on('checkout_error', function(){
    for (let i = 0; i < steps.length; i++){
        let stepSelector = steps[i].selector;
        let fields = stepSelector + ' p';
        $( fields ).each(function() {
            if ( $(this).hasClass('woocommerce-invalid') ) {
                sessionStorage.setItem('checkout_step', i);
                showCurrentStep();
                return false;
            }
        });
    }
});

XSLTProcessor not running

Have been knocking my head trying to figure why the following XSLTProcessor call is not working.

The XSL-T

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xml:space="default">
    <xsl:output method="text" version="1.0" encoding="UTF-8" indent="no"/>
    <xsl:strip-space elements="*"/>
    <xsl:param name="include-header" select="'false'"/>
    <xsl:template match="/">
       <!--xsl:element name="row"-->
       <xsl:text>{</xsl:text>
        <xsl:apply-templates select="*"/>
        <!--/xsl:element-->
       <xsl:text>}</xsl:text>
    </xsl:template>
    <xsl:template match="*[count(descendant::*)=0]">
        <xsl:param name="parent"/>
        <xsl:variable name="quote" select="'&quot;'"/>
        <xsl:variable name="thisName" select="name()"/>
        <xsl:variable name="precedingSibling" select="count(preceding-sibling::*[name()=$thisName])+1"/>
        <xsl:variable name="parentChild" select="concat($parent, '.',$thisName, $precedingSibling)"/>
        <xsl:value-of select="concat($quote,$parentChild, $quote, ': ', $quote, ., $quote, ',')"/>
        <xsl:text>
</xsl:text>
    </xsl:template>
    <xsl:template match="*">
        <xsl:call-template name="recurse-descendents"/>
    </xsl:template>
    <xsl:template match="*[count(descendant::*)>0]">
        <xsl:call-template name="recurse-descendents"/>
    </xsl:template>
    <xsl:template name="recurse-descendents">
        <xsl:variable name="thisName" select="name()"/>
        <xsl:apply-templates select="*[count(descendant::*)=0]">
            <xsl:with-param name="parent" select="concat($thisName, count(preceding-sibling::*[name()=$thisName])+1)"/>
        </xsl:apply-templates>
        <xsl:apply-templates select="*[count(descendant::*)>0]"/>
    </xsl:template>
</xsl:stylesheet>

Sample XML

<?xml version="1.0" encoding="UTF-8"?>
<foods>
    <meats>
        <meat>Beef</meat>
        <meat>Chicken</meat>
        <meat>Lamb</meat>
    </meats>
    <fruits>
        <fruit>Orange</fruit>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
        <fruit>Avacado</fruit>
    </fruits>
    <vegetables>
        <vegetable>Carrot</vegetable>
        <vegetable>Cellery</vegetable>
        <vegetable>Potato</vegetable>
    </vegetables>
</foods>

Output from XML Spy (as expected)

{"meats1.meat1": "Beef",
"meats1.meat2": "Chicken",
"meats1.meat3": "Lamb",
"fruits1.fruit1": "Orange",
"fruits1.fruit2": "Apple",
"fruits1.fruit3": "Banana",
"fruits1.fruit4": "Avacado",
"vegetables1.vegetable1": "Carrot",
"vegetables1.vegetable2": "Cellery",
"vegetables1.vegetable3": "Potato",
}

Javascript code using XSLTProcessor (not working)

async function GenerateTestCaseResponse(xml, testCase) {
    const domParser = new DOMParser();
    const xsltProcessor = new XSLTProcessor();

    const xslResponse = await fetch("transformer/generate-response-json.xslt");
    const xslText = await xslResponse.text();
    const xslStylesheet = domParser.parseFromString(xslText, "application/xml");
    xsltProcessor.importStylesheet(xslStylesheet);
    var responseDomParser = new DOMParser();
    var responseDocument = responseDomParser.parseFromString(xml, "text/xml");
    var result =  xsltProcessor.transformToDocument(responseDocument);
    console.log(result.body);
    return result;
}

The call to xsltProcessor.transformToDocument returns empty with no error or exception. At a loss how to resolve, and any thoughts gratefully received.

need to write algorithm for this question in javascript [closed]

given 2 strings p and Q each consisting of N lowercase english letters for each position in the strings we have to choose one letter from either P and Q in order to construct a new String S, such that the number of distinct letters is S is minmal. Our task is to find the number of distinct letters in resulting string for example P=”abc, Q=”bcd”, your function should return 2 all possible strings s that can be constructed are “abc, “abd”, “acc”,”acd”, “bbc”, “bbd”, “bcc”,”bcd the minimum number of dsitinct letters is 2 which be obtained by constructing the follwing strings “acc”, “bbc”,”bbd”, “bcc” given P=”axxz”, Q=”yzwy”, your function should return 2 string S must consist of at least 2 distinct letters in this case we can construct S=”yxxy” where the number of distinct letters is equal to 2 and this is the only optimal solution given P=”bacad
, Q=”abada, your function should return 1 we can choose the letter ‘a’ in each position, so S can be equal to “aaaa”. given P = “amz”, Q=”amz” your function should return 3 the the input string are identical so the only possible S that can be constructed is “amz” and its number of distinct letter is 3 write the efficient algorithm for the follwoing assumption N is an inetger within the range [1…200,000] string P and Q are both of length N strings P and Q are made only of lowercase letters(a-z) string P and Q contain a total of at most 20 distinct letters

Need answer for this javascript question

Javascript if statement is executing on false condition

const value = '2555-555-5555';
const regex = /(1s?)?(d{3}|(d{3}))[-s]?d{3}[-s]?d{4}/; //I found this is an incorrect regex

if (regex.test(value)) {
  console.log(regex.test(value)); //is false
  resultsDiv.querySelector("p").textContent = `Valid US number: ${value}`;
} else {
  resultsDiv.querySelector("p").textContent = `Invalid US number: ${value}`;
}

The if condition here should not be executing.

drag and drop box showing stop sign

I want to be able to drag and drop the draggable box to any other date and it should remove that previous one.
For example if I move drag box from 5th march to 6th march it should remove from 5th march and update to 6th march
my problem is when I drag and drop this box it shows a stop sign and I cannot move it. Is there any way to fix it or any other way so I can move my boxes to another date along with its data (has some data name and subrub when you hover over drag box?
enter image description here

my code for runsheetpreview.js

import React, { useState, useRef } from "react";
import { startOfMonth, endOfMonth, startOfWeek, endOfWeek, format, addDays, addMonths, subMonths, isSameMonth } from "date-fns";
import "../assets/css/RunSheetPDF.css";

const DraggableBox = ({ day, onDrop, name: initialName, suburb: initialSuburb }) => {
  const [editable, setEditable] = useState(false);
  const [name, setName] = useState(initialName);
  const [suburb, setSuburb] = useState(initialSuburb);
  const [showTooltip, setShowTooltip] = useState(false);
  const boxRef = useRef(null);

  const handleDoubleClick = () => {
    setEditable(true);
  };

  const handleChangeName = (e) => {
    setName(e.target.value);
  };

  const handleChangeSuburb = (e) => {
    setSuburb(e.target.value);
  };

  const handleBlur = () => {
    setEditable(false);
  };

  const handleDragStart = () => {
    setShowTooltip(false);
    boxRef.current.classList.add('dragging');
  };

  const handleDragEnd = () => {
    boxRef.current.classList.remove('dragging');
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  const handleDrop = (e) => {
    e.preventDefault();
    const draggedDay = parseInt(e.dataTransfer.getData("text/plain"));
    onDrop(draggedDay, day);
  };

  return (
    <div
      className="drag-box"
      ref={boxRef}
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDoubleClick={handleDoubleClick}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      onMouseEnter={() => setShowTooltip(true)}
      onMouseLeave={() => setShowTooltip(false)}
      style={{
        width: "70px",
        height: "80px",
        textAlign: "center",
        backgroundColor: "#F5F5F5",
        color: "#333333",
        marginTop: "5px",
        position: "relative",
        cursor: "move" // Set cursor to move when hovering over the box
      }}
    >
      <p style={{ margin: 0, lineHeight: "80px" }}>{day}</p>
      {showTooltip && (
        <div className="tooltip">
          <p>Name: {name}</p>
          <p>Suburb: {suburb}</p>
        </div>
      )}
    </div>
  );
};

const RunSheetPreview = () => {
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [calendarData, setCalendarData] = useState([
    { day: 5, name: "John", suburb: "Suburb 1" },
    { day: 15, name: "Alice", suburb: "Suburb 2" },
    { day: 25, name: "Bob", suburb: "Suburb 3" },
    { day: 27, name: "Eva", suburb: "Suburb 4" }
  ]);

  const handleDrop = (draggedDay, dropDay) => {
    const newData = [...calendarData];
    const draggedItem = newData.find(item => item.day === draggedDay);
    draggedItem.day = dropDay;
    setCalendarData(newData);
  };

  const generateCalendar = () => {
    const monthStart = startOfMonth(selectedDate);
    const monthEnd = endOfMonth(selectedDate);
    const startDate = startOfWeek(monthStart, { weekStartsOn: 0 });
    const endDate = endOfWeek(monthEnd, { weekStartsOn: 0 });

    const rows = [];
    let days = [];
    let day = startDate;

    while (day <= endDate) {
      for (let i = 0; i < 7; i++) {
        const dayOfMonth = format(day, "d");
        const isCurrentMonth = isSameMonth(day, monthStart);
        const draggableData = calendarData.find(item => item.day === parseInt(dayOfMonth));
        const draggableBoxExists = draggableData !== undefined;

        days.push(
          <td key={day} style={{ width: "70px", height: "80px" }}>
            {isCurrentMonth && (
              <div>
                {draggableBoxExists ? (
                  <DraggableBox
                    day={draggableData.day}
                    name={draggableData.name}
                    suburb={draggableData.suburb}
                    onDrop={handleDrop}
                  />
                ) : (
                  <p>{dayOfMonth}</p>
                )}
              </div>
            )}
          </td>
        );
        day = addDays(day, 1);
      }
      rows.push(<tr key={day}>{days}</tr>);
      days = [];
    }

    return rows;
  };

  const handleNextMonth = () => {
    setSelectedDate(addMonths(selectedDate, 1));
  };

  const handlePreviousMonth = () => {
    setSelectedDate(subMonths(selectedDate, 1));
  };

  return (
    <div style={{ width: "100%", display: "flex", flexDirection: "column", alignItems: "center", marginTop: "20px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", marginBottom: "0px" }}>
        <button onClick={handlePreviousMonth} style={{ backgroundColor: "#F5F5F5", color: "#333333", border: "1px solid #CCCCCC", borderRadius: "5px", padding: "5px 10px", marginRight: "10px" }}>Previous Month</button>
        <h2 style={{ color: "#333333", margin: 0 }}>{format(selectedDate, "MMMM yyyy")}</h2>
        <button onClick={handleNextMonth} style={{ backgroundColor: "#F5F5F5", color: "#333333", border: "1px solid #CCCCCC", borderRadius: "5px", padding: "5px 10px", marginLeft: "10px" }}>Next Month</button>
      </div>
      <div className="calendar-container">
        <table className="calendar-table">
          <thead>
            <tr>
              <th>Sun</th>
              <th>Mon</th>
              <th>Tue</th>
              <th>Wed</th>
              <th>Thu</th>
              <th>Fri</th>
              <th>Sat</th>
            </tr>
          </thead>
          <tbody>
            {generateCalendar()}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default RunSheetPreview;

my code for RunSheetPDF.css

.centered-text {
  text-align: center;
  font-weight: 700;
}

.title {
  text-align: left;
  font-weight: bold;
  font-size: 30px;
  text-transform: uppercase;
  font-style: bold;
}

.table-container {
  width: 1000px;
  background: white;
  font-family: "Times New Roman";
}

.table {
  width: 90%;
  border-collapse: collapse;
}

.top-header th {
  text-align: left;
  border: none;
}

.table-body td {
  text-align: left;
  border: none;
}

.paper {
  padding: 20px;
  display: flex;
  justify-content: space-between;
}

.left-content {
  flex: 1;
  text-align: left;
}

.right-content {
  flex: 1;
  text-align: left;
}

.flex-content {
  display: flex;
  justify-content: space-between;
}

.empty-box {
  text-align: left;
}

.border-box {
  width: 100px;
  height: 20px;
  border: 1px solid #000;
}

.bold-text {
  font-weight: bold;
}

.normal-text {
  font-weight: normal;
}

.text-left {
  text-align: left;
  font-family: "Times New Roman", Times, serif;
}

.no-border {
  border: none;
}
.page-content {
  height: 38rem;
  overflow: auto;
  border: solid 1px black;
  margin: 0 80mm 30mm 45mm;
  width: 35rem;
  page-break-after: always;
}

/* Use media query to apply styles only when printing */
@media print {
  .page-content {
    page-break-before: always; /* This will force a page break before each .page-content element */
  }
}

/* Add this to your CSS file or CSS module */
.print-button-wrapper {
  position: fixed;
  bottom: 130px; /* Adjust this value to change the vertical position */
  right: 150px; /* Adjust this value to change the horizontal position */
}

.calendar-container {
  margin: 20px auto;
  max-width: 800px;
  background-color: #f2f2f2;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.calendar-table {
  width: 100%;
  border-collapse: collapse;
}

.calendar-table th, .calendar-table td {
  padding: 10px;
  text-align: center;
  border: 2px solid #fff; /* White border to separate cells */
}

.calendar-table th {
  background-color: #3f51b5; /* Dark blue background for days */
  color: #fff;
  font-weight: bold;
  font-size: 18px;
}

.calendar-table td {
  background-color: #ffffff; /* White background for date cells */
}

.calendar-table td:first-child {
  background-color: #f5f5f5; /* Light gray background for first column */
}

.drag-box {
  padding: 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  cursor: pointer;
}

.drag-box p {
  margin: 5px 0;
}

.drag-box input {
  width: 100%;
  padding: 5px;
  margin-bottom: 5px;
}

.drag-box.draggable {
  background-color: #ffd700; /* Gold background for draggable box */
  border-color: #ffd700;
  color: #000;
}

.drag-box.draggable p {
  color: #000;
}


.drag-box {
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 5px;
  padding: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 100px; /* Adjust the width as needed */
  height: 60px; /* Adjust the height as needed */
  transition: opacity 0.3s ease; /* Add transition for smooth hide/show effect */
}

.drag-box.hidden {
  opacity: 0; /* Hide the box during drag */
}

.calendar-table {
  border-collapse: collapse;
  width: 100%; /* Make the table fill its container */
  background-color: #f0e8ff; /* Light purple background color */
}

.calendar-table th,
.calendar-table td {
  border: 1px solid #cccccc;
  padding: 8px;
  text-align: center;
  width: 100px; /* Adjust the width of table cells */
}
.drag-box {
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  margin: 2px;
}

.calendar-table {
  width: 100%;
}

.calendar-table td {
  border: 1px solid #ccc;
  padding: 5px;
  text-align: center;
}

.calendar-table p {
  margin: 0;
}
.drag-box {
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  margin: 2px;
  position: relative; /* Add relative positioning */
}

.tooltip {
  position: absolute;
  top: 100%; /* Position below the draggable box */
  left: 50%; /* Center horizontally */
  transform: translateX(-50%); /* Center horizontally */
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  z-index: 1; /* Ensure tooltip appears above other elements */
  white-space: nowrap; /* Prevent line breaks */
  visibility: hidden; /* Initially hidden */
}

.drag-box:hover .tooltip {
  visibility: visible; /* Show tooltip on hover */
}

How do I remove an item from localStorage and update the state once removed?

// **Card.jsx code**

import { useState, useEffect } from "react";
import "./card.scss";

function Card({ movieList, removeMovie }) {
  const [saved, setSaved] = useState(null);

  const handleButtonClick = (movie) => {
    setSaved(saved === movie ? null : movie);
    if (saved === movie) {
      setSavedMovies((prev) => prev.filter((item) => item !== movie));
      removeMovie(movie);
    } else {
      setSavedMovies((prev) => [...prev, movie]);
    }
  };

  const handleDelete = (movie) => {
    const filtered = movieList.filter((item) => {
      return item !== movie;
    });
    setSavedMovies(filtered);
  };

  const [savedMovies, setSavedMovies] = useState([]);

  useEffect(() => {
    const retrieveSavedMovies = () => {
      const savedMovies = localStorage.getItem("savedMovies");

      return savedMovies ? JSON.parse(savedMovies) : [];
    };

    setSavedMovies(retrieveSavedMovies());
  }, []);

  useEffect(() => {
    localStorage.setItem("savedMovies", JSON.stringify(savedMovies));
  }, [savedMovies]);

  return (
    <div className="cardContainer">
      {movieList.map((movie) => (
        <div className="card" key={movie.id}>
          <div className="save">
            <button
              onClick={() => {
                handleButtonClick(movie);
              }}
              className={`button ${saved === movie ? "saved" : ""}`}
            >
              {saved === movie ? (
                <img src="/star.png" alt="" />
              ) : (
                <img src="/trash.png" alt="" />
              )}
            </button>
          </div>
          <img
            src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`}
            alt=""
          />
          <p>{movie.title}</p>
        </div>
      ))}
    </div>
  );
}

export default Card;

// **SavedMovie.jsx code**

import "./savedMovie.scss";
import { useState, useEffect } from "react";
import Card from "../card/Card";

function SavedMovie() {
  const [savedMovies, setSavedMovies] = useState([]);

  useEffect(() => {
    const retrieveSavedMovies = () => {
      const savedMovies = localStorage.getItem("savedMovies");
      return savedMovies ? JSON.parse(savedMovies) : [];
    };

    setSavedMovies(retrieveSavedMovies());
  }, []);

  return (
    <div className="savedMovie">
      <div className="body">
        <div className="content">
          {savedMovies.length > 0 ? (
            <Card movieList={savedMovies} />
          ) : (
            <p>No saved movies</p>
          )}
        </div>
      </div>
    </div>
  );
}

export default SavedMovie;


Hello, I’m trying to create a movie list app with react. I have 2 tabs, the first one being “Movies” which is also the homepage, where I display a list of movies using TMDB API, and the second tab is “To Watch” where I display all the movies the user chose to save by clicking on the button. How do I remove the movie from the “To Watch” tabs when the user clicks on the same button?

I tried creating a removeMovie function and passing it to the Card component as props and then call it in the handleButtonClick function which is being called by the button onClick. However nothing actually happened.

How to I can view background apps in a React Native application?

I’m working on a Gaming Social Media app with react native and I need to access information about background apps running on the device. Specifically, I want to retrieve a list of background apps along with their information such as the time when it started and package name. to set status automatically for ex: “playing {game name}” if user allow me.

I’ve searched through the React Native documentation and various libraries, but I couldn’t find a clear solution for this. Is there a native module or library available that allows me to achieve this functionality? If not, what would be the recommended approach to implement this feature in a React Native application?

Any guidance or suggestions would be greatly appreciated. Thank you!