Ball keeps getting stuck at wall borders in PONG remake on MIT Scratch

I am designing a pong game remake for a class project and my ball keeps getting stuck going back and forth on certain walls…

This is the block responsible for detecting wall collisions and reversing the direction of the ball:

pong remake

I have tried to rearrange the logic in several ways to no avail, even though on paper it should be working… Scratch unfortunately does not allow operators such as >=, so I have to use if x > y or x = y… Also, it seems as though the if statements do not run, since I tried changing the backdrop when it collides and it doesn’t trigger that either…

Best Dashboard Tools for Firestore/JSON Data in a React Web App

I’m building a web app using React and storing data in Firestore and JSON files. I need to create a dashboard that:

-Provides strong data analytics capabilities
-Offers data visualization options
-Is easy to develop for beginners

I’m looking for recommendations on the best, fastest, and most efficient tools that:

-Can easily integrate with Firestore or JSON files as data sources
-Work well with React for web development
-Support real-time data updates (especially for Firestore)
-Are beginner-friendly (ideally with drag-and-drop functionality or simple API -integration)
-Offer good data analysis and visualization features

What dashboard tools would you suggest that meet these criteria? Any tips on how to integrate them with React and connect them to Firestore/JSON data would be greatly appreciated.

Using hasOwnProperty for nested object keys if key name is a number

I’m currently building a Pokémon application, therefor I’m accessing data from PokéAPI and will store specific data in a variable, such as name, id and type.

Currently I’m facing issues to store the second type of a pokémon. Some of them have one type, some of them have two.

If a pokémon has two types the data structure looks like this:
Bulbasaur JSON data screenshot from pokeapi.co/api/v2/pokemon/bulbasaur

Here’s the link to JSON data for an example pokémon with 1 types: https://pokeapi.co/api/v2/pokemon/bulbasaur

If a pokémon only has one type the structure looks like this:
Togepi JSON data screenshot from https://pokeapi.co/api/v2/pokemon/togepi

Link: https://pokeapi.co/api/v2/pokemon/togepi

To check whether there’s a second type or not I wrote a function:

function CheckPropertySecondtype(str) {
  if (str.hasOwnProperty("types"[1])) {
    pokemondata.secondtype = str.types[1].type.name;
    console.log("Pokemon has a second type");
  } else {
    pokemondata.secondtype = "none";
    console.log(str.types[1].type.name);
  }
}

The problem is, that the if statement doesn’t work the way I want it to. It’s always false which means no matter if there’s a second type or not, the output is always “none”. I tried several notations like hasOwnProperty(types[1].type.name) or hasOwnProperty(types1.type.name).

How can I access the key correctly to check this?

Using hasOwnProperty for nested object keys if key name is a number

I’m currently building a Pokémon application, therefor I’m accessing data from PokéAPI and will store specific data in a variable, such as name, id and type.

Currently I’m facing issues to store the second type of a pokémon. Some of them have one type, some of them have two.

If a pokémon has two types the data structure looks like this:
Bulbasaur JSON data screenshot from pokeapi.co/api/v2/pokemon/bulbasaur

Here’s the link to JSON data for an example pokémon with 1 types: https://pokeapi.co/api/v2/pokemon/bulbasaur

If a pokémon only has one type the structure looks like this:
Togepi JSON data screenshot from https://pokeapi.co/api/v2/pokemon/togepi

Link: https://pokeapi.co/api/v2/pokemon/togepi

To check whether there’s a second type or not I wrote a function:

function CheckPropertySecondtype(str) {
  if (str.hasOwnProperty("types"[1])) {
    pokemondata.secondtype = str.types[1].type.name;
    console.log("Pokemon has a second type");
  } else {
    pokemondata.secondtype = "none";
    console.log(str.types[1].type.name);
  }
}

The problem is, that the if statement doesn’t work the way I want it to. It’s always false which means no matter if there’s a second type or not, the output is always “none”. I tried several notations like hasOwnProperty(types[1].type.name) or hasOwnProperty(types1.type.name).

How can I access the key correctly to check this?

Loading module was blocked because of a disallowed MIME type(“text/html”)

I am unable to import GLTFLoader into my threejs website & it’s showing the same error again and again i.e.
” Loading module “http://127.0.0.1:5500/node_modules/three/examples/jsm/loaders/node_modules/three” was blocked because of a disallowed MIME type(“text/html”) “.

This is my main.js code:-

             import * as THREE from "./node_modules/three/build/three.module.js";
            import {GLTFLoader} from "./node_modules/three/examples/jsm/loaders/GLTFLoader.js";
            // Basic Three.js setup
            const scene= new THREE.Scene();
            const camera=new THREE.PerspectiveCamera( 75,0.1,1000);                                               
            const renderer= new THREE.WebGLRenderer({
            canvas: document.querySelector('#bg'),
            });
            renderer.setPixelRatio(window.devicePixelRatio);
            renderer.setSize(window.innerWidth,window.innerHeight);
            camera.position.setZ(30);
            renderer.render(scene,camera);
            // Load the GLB model
            const loader= new GLTFLoader();
            loader.load('C:UsersUserDesktoprealistic_human_heart.glb', (gltf) => {
            const heart = gltf.scene;
            scene.add(heart);
            heart.position.set(0, 0, 0); // Center the model 
            }, undefined, (error) => {
            console.error(error);
            });

            // Position the camera
            camera.position.z = 5;

            // Animation loop
            function animate() {
            requestAnimationFrame(animate);
            if (scene.children.length > 1) { // Check if the heart model is loaded
            scene.children[1].rotation.y += 0.01; // Rotate the heart
            }
            renderer.render(scene, camera);
            }
            animate();

Loading module was blocked because of a disallowed MIME type(“text/html”)

I am unable to import GLTFLoader into my threejs website & it’s showing the same error again and again i.e.
” Loading module “http://127.0.0.1:5500/node_modules/three/examples/jsm/loaders/node_modules/three” was blocked because of a disallowed MIME type(“text/html”) “.

This is my main.js code:-

             import * as THREE from "./node_modules/three/build/three.module.js";
            import {GLTFLoader} from "./node_modules/three/examples/jsm/loaders/GLTFLoader.js";
            // Basic Three.js setup
            const scene= new THREE.Scene();
            const camera=new THREE.PerspectiveCamera( 75,0.1,1000);                                               
            const renderer= new THREE.WebGLRenderer({
            canvas: document.querySelector('#bg'),
            });
            renderer.setPixelRatio(window.devicePixelRatio);
            renderer.setSize(window.innerWidth,window.innerHeight);
            camera.position.setZ(30);
            renderer.render(scene,camera);
            // Load the GLB model
            const loader= new GLTFLoader();
            loader.load('C:UsersUserDesktoprealistic_human_heart.glb', (gltf) => {
            const heart = gltf.scene;
            scene.add(heart);
            heart.position.set(0, 0, 0); // Center the model 
            }, undefined, (error) => {
            console.error(error);
            });

            // Position the camera
            camera.position.z = 5;

            // Animation loop
            function animate() {
            requestAnimationFrame(animate);
            if (scene.children.length > 1) { // Check if the heart model is loaded
            scene.children[1].rotation.y += 0.01; // Rotate the heart
            }
            renderer.render(scene, camera);
            }
            animate();

Leaflet sidebar plugin and markers

I have the following HTML/PHP page, where I use Leaflet JS and the plugin Leaflet Sidebar. Two markers should be shown on the map and when they are clicked upon a sidebar should open with some information (retrieved via PHP in my case).

I must have something wrong because the map shows up without the two markers.
I can’t spot the problem. Can you please give some hints?

<html>
 <head>
  <title>map</title>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.95/themes/smoothness/jquery-ui.css">
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-sA+zWATbFveLLNqWO2gtiw3HL/lh1giY/Inf1BJ0z14=" crossorigin=""/>
  <link rel="stylesheet" href="css/L.Control.Sidebar.css" />

  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.95/jquery-ui.js"></script>
</head>
<body>
<?php

A FEW PHP VARIABLES TO BE ECHOED IN THE SIDEBAR...

$lat1 = $objResult["lat1"];
$lon1 = $objResult["lon1"];
$cap1 = htmlspecialchars(addslashes($objResult["cap1"]));
$testo1=nl2br(addslashes($objResult["testo1"]));

$lat2 = $objResult["lat2"];
$lon2 = $objResult["lon2"];
$cap2 = htmlspecialchars(addslashes($objResult["cap2"]));
$testo2=nl2br(addslashes($objResult["testo2"]));
?>
<center>
 <div id="map" class="embed-container"></div>
</center>

<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-o9N1jGDZrf5tS+Ft4gbIK7mYMipq9lqpVJ91xHSyKhg=" crossorigin=""></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier-Leaflet/0.2.6/oms.min.js"></script>
<script src="js/L.Control.Sidebar.js"></script>
<script>
var map = L.map('map').setView([34.169090845221135, 27.773437499999996], 3);
L.control.scale({imperial: false}).addTo(map);

var oms = new OverlappingMarkerSpiderfier(map);

var pol = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    minZoom: 3,
    maxZoom: 9
  }).addTo(map);

var sat = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
  {
    attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
    minZoom: 3,
    maxZoom: 9
  });

var baseMaps = {
    "politica": pol,
    "satellitare": sat
};
L.control.layers(baseMaps, overlayMaps).addTo(map);
</script>

<script>
  var map = L.map('map').setView([34.169090845221135, 27.773437499999996], 3);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      maxZoom: 8,
      minZoom: 3
    }).addTo(map);
</script>
<script>
        var sidebar_1 = L.control.sidebar('sidebar_1', {
            closeButton: true,
            position: 'left'
        });

        sidebar_1.setContent('<b>Capitolo 1</b>: <?=$cap1;?><br><br><?=$testo1;?><br>');

        map.addControl(sidebar_1);
        setTimeout(function () {
            sidebar_1.hide();
        }, 500);

        var marker1 = L.marker([<?php echo $lat1;?>, <?php echo $lon1;?>]).addTo(map).on('click', function () {
            sidebar_1.toggle();
        });
</script>
<script>
        var sidebar_2 = L.control.sidebar('sidebar_2', {
            closeButton: true,
            position: 'left'
        });

        sidebar_2.setContent('<b>Capitolo 2</b>: <?=$cap2;?><br><br><?=$testo2;?><br>');

        map.addControl(sidebar_2);
        setTimeout(function () {
            sidebar_2.hide();
        }, 500);

        var marker2 = L.marker([<?php echo $lat2;?>, <?php echo $lon2;?>]).addTo(map).on('click', function () {
            sidebar_2.toggle();
        });
</script>
<script>
 oms.addListener('spiderfy', function(markers) {
  for (var i = 0, len = markers.length; i < len; i ++) markers[i].setIcon(new lightIcon());
  map.closePopup();
 });
 oms.addListener('unspiderfy', function(markers) {
  for (var i = 0, len = markers.length; i < len; i ++) markers[i].setIcon(new darkIcon());
 });
</script>
<script>
var latlngs = Array();

//Get latlng from each marker
latlngs.push(marker1.getLatLng());
latlngs.push(marker2.getLatLng());

//From documentation https://leafletjs.com/reference.html#polyline
// create a red polyline from an arrays of LatLng points
var polyline = L.polyline(latlngs,
{
color: 'purple',
weight: 7,
opacity: 0.7,
dashArray: '20,15',
lineJoin: 'round'
}).addTo(map);

// zoom the map to the polyline
map.fitBounds(polyline.getBounds());
</script>

</body>
</html>

Leaflet sidebar plugin and markers

I have the following HTML/PHP page, where I use Leaflet JS and the plugin Leaflet Sidebar. Two markers should be shown on the map and when they are clicked upon a sidebar should open with some information (retrieved via PHP in my case).

I must have something wrong because the map shows up without the two markers.
I can’t spot the problem. Can you please give some hints?

<html>
 <head>
  <title>map</title>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.95/themes/smoothness/jquery-ui.css">
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-sA+zWATbFveLLNqWO2gtiw3HL/lh1giY/Inf1BJ0z14=" crossorigin=""/>
  <link rel="stylesheet" href="css/L.Control.Sidebar.css" />

  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.95/jquery-ui.js"></script>
</head>
<body>
<?php

A FEW PHP VARIABLES TO BE ECHOED IN THE SIDEBAR...

$lat1 = $objResult["lat1"];
$lon1 = $objResult["lon1"];
$cap1 = htmlspecialchars(addslashes($objResult["cap1"]));
$testo1=nl2br(addslashes($objResult["testo1"]));

$lat2 = $objResult["lat2"];
$lon2 = $objResult["lon2"];
$cap2 = htmlspecialchars(addslashes($objResult["cap2"]));
$testo2=nl2br(addslashes($objResult["testo2"]));
?>
<center>
 <div id="map" class="embed-container"></div>
</center>

<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-o9N1jGDZrf5tS+Ft4gbIK7mYMipq9lqpVJ91xHSyKhg=" crossorigin=""></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier-Leaflet/0.2.6/oms.min.js"></script>
<script src="js/L.Control.Sidebar.js"></script>
<script>
var map = L.map('map').setView([34.169090845221135, 27.773437499999996], 3);
L.control.scale({imperial: false}).addTo(map);

var oms = new OverlappingMarkerSpiderfier(map);

var pol = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    minZoom: 3,
    maxZoom: 9
  }).addTo(map);

var sat = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
  {
    attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
    minZoom: 3,
    maxZoom: 9
  });

var baseMaps = {
    "politica": pol,
    "satellitare": sat
};
L.control.layers(baseMaps, overlayMaps).addTo(map);
</script>

<script>
  var map = L.map('map').setView([34.169090845221135, 27.773437499999996], 3);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      maxZoom: 8,
      minZoom: 3
    }).addTo(map);
</script>
<script>
        var sidebar_1 = L.control.sidebar('sidebar_1', {
            closeButton: true,
            position: 'left'
        });

        sidebar_1.setContent('<b>Capitolo 1</b>: <?=$cap1;?><br><br><?=$testo1;?><br>');

        map.addControl(sidebar_1);
        setTimeout(function () {
            sidebar_1.hide();
        }, 500);

        var marker1 = L.marker([<?php echo $lat1;?>, <?php echo $lon1;?>]).addTo(map).on('click', function () {
            sidebar_1.toggle();
        });
</script>
<script>
        var sidebar_2 = L.control.sidebar('sidebar_2', {
            closeButton: true,
            position: 'left'
        });

        sidebar_2.setContent('<b>Capitolo 2</b>: <?=$cap2;?><br><br><?=$testo2;?><br>');

        map.addControl(sidebar_2);
        setTimeout(function () {
            sidebar_2.hide();
        }, 500);

        var marker2 = L.marker([<?php echo $lat2;?>, <?php echo $lon2;?>]).addTo(map).on('click', function () {
            sidebar_2.toggle();
        });
</script>
<script>
 oms.addListener('spiderfy', function(markers) {
  for (var i = 0, len = markers.length; i < len; i ++) markers[i].setIcon(new lightIcon());
  map.closePopup();
 });
 oms.addListener('unspiderfy', function(markers) {
  for (var i = 0, len = markers.length; i < len; i ++) markers[i].setIcon(new darkIcon());
 });
</script>
<script>
var latlngs = Array();

//Get latlng from each marker
latlngs.push(marker1.getLatLng());
latlngs.push(marker2.getLatLng());

//From documentation https://leafletjs.com/reference.html#polyline
// create a red polyline from an arrays of LatLng points
var polyline = L.polyline(latlngs,
{
color: 'purple',
weight: 7,
opacity: 0.7,
dashArray: '20,15',
lineJoin: 'round'
}).addTo(map);

// zoom the map to the polyline
map.fitBounds(polyline.getBounds());
</script>

</body>
</html>

React Props Issue: Red Underscores and Unexpected Behavior

Hi everyone!

Recently, I have been working on a Meme Project with ReactJs as the Frontend. It is basically a simple app that lets users make memes fast and effectively. Until, I woke up yesterday with a very weird problem. VS Code indicates that there is a problem with using Props in the Components. Which, I have been trying to resolve since yesterday Unfurtunately, It’s decreasing my productivity.
Even AI could not handle the problem.

Problem 1: Props in all Components have red lines under them.

  • Example line: Line 12 in Oome Component
  • function Oome ({savedMemes, setSavedMemes}) {...}

Problem 2: Props are not working as expected and have red line under each.

  • Example line: Line 106 in TextInput Component
  • {(memeText.status.top.isMoreOn) && <p>more is on</p>}

Note: Typos in the code are intentional. Because my keyboard has missing letters. 🙂

Debugging Attempts:

  • Using Props: I used the instead of calling the property directly
  • Simplifying: I simplify the code. Hopping that the problem comes from its complication.

Unfortunatly, both ways did not change in the problem.

Code below has {/* Code With Problem */} over the lines mentioned under each previous problem in the post.

Current Code:

  • App Component:
import{ useEffect, useState } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from "./Pages/Home/Oome";
import UserMemes from "./Pages/UserMemes/UserMemes";

const App = () => {
  const {savedMemes, setSavedMemes } = useState([]);

  useEffect(() => {
    console.log(savedMemes)
  }, [savedMemes])

  return (
    <Router>
      <Routes>
        <Route
          path="/"
          element={
            <Home savedMemes={savedMemes} setSavedMemes={setSavedMemes}
              
            />
          }
        />
        <Route path="/jallary" element={<UserMemes savedMemes={savedMemes} setSavedMemes={setSavedMemes} />} />
      </Routes>
    </Router>
  );
};

export default App;

  • Oome Component:
import { useEffect, useState , useRef} from "react";
import "./Oome.css";
import Navbar from "../../Components/NavBar/Navbar";
import BottomeNavBar from "../../Components/BottomNavBar/BottomNavBar";
import Preview from "../../Components/Preview/Preview";
import TextInput from "../../Components/TextInput/TextInput";

import html2canvas from "html2canvas";
import { Download } from "../../Components/Download/Download";
import { GetMemeButton } from "../../Components/GetMemeButton/GetMemeButton";

{/* Code With Problem */}
function Oome ({savedMemes, setSavedMemes}) {
  const [selectedFile, setSelectedFile] = useState(``);
  const imeRef = useRef()

  function andleDownload() {
    html2canvas(imeRef.current, { useCORS: true }).then((canvas) => {
        const link = document.createElement("a");
        link.href = canvas.toDataURL("image/png");
        link.download = "download.png";
        link.click();
      });
  }

  const [memeText, setMemeText] = useState({
    top: {
      topText: ``,
      color: ``,
    },
    bottom: {
      bottomText: ``,
      color: ``,
    },
    imae: {
        data: null,
      },
    status : {
        date: null,
        top: {
          isMoreOn: false
        },
        bottom: {
          isMoreOn: false
        }
    }
  });

 

  useEffect(() => {
    if (selectedFile) {
      setMemeText((prevMemeText) => ({
        ...prevMemeText,
        imae: {
          data: selectedFile,
        },
        status : {
            date: new Date().getHours(),
            
            top: {
              isMoreOn: false,
            },
            bottom: {
              isMoreOn: false,
            }
        }
      }));
    }
    // savedMemes()
  }, [selectedFile]);

  
  return (
    <div className="oome-container">
      <Navbar setSelectedFile={setSelectedFile} />
      <Preview 
        selectedFile={selectedFile} 
        memeText={memeText}
        savedMemes={savedMemes}
        imeRef={imeRef}
      />
      <TextInput
        memeText={memeText}
        setMemeText={setMemeText}
        setSavedMemes={setSavedMemes}
        savedMemes={savedMemes}
        andleDownload={andleDownload}
      />
      
        <Download andleDownload={andleDownload}/>
        <GetMemeButton />
      <BottomeNavBar />
    </div>
  );
};

export default Oome;
  • TextInput Component:
import { useState } from 'react';
import './TextInput.css';

const TextInput = ({setMemeText, memeText, setSavedMemes, savedMemes}) => {
    
    

    function andleTopText(event) {
        const topText = event.target.value
        console.log(topText)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                top : {
                    ...prevMemeText.top,
                    topText: topText,
                }
                
            }
        ))
    }
    function andleTopColor(event) {
        const topColor = event.target.value
        console.log(topColor)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                top : {
                    ...prevMemeText.top,
                    color: topColor
                }
                
            }
        ))
    }
    function andleBottomText(event) {
        const bottomText = event.target.value
        console.log(bottomText)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                bottom : {
                    ...prevMemeText.top,
                    bottomText:bottomText
                }
                
            }
        ))
    }

    function andleBottomColor(event) {
        const bottomColor = event.target.value
        console.log(bottomColor)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                bottom : {
                    ...prevMemeText.top,
                    color: bottomColor 
                }
                
            }
        ))
    }

    function andleSaveMeme() {
        setSavedMemes(prevSavedMemes => ([
            ...prevSavedMemes,
            memeText
        ]))
        console.log(`savedMemes: `, savedMemes)
    }

    const [isMoreOn, setIsMoreOn] = useState(false)

    function andleMoreClick(position) {
        setIsMoreOn((prev) => !prev)
        setMemeText((prev) => ({
            ...prev,
            status: {
                ...status,
                [position]: isMoreOn
            }
        }) 
        )
    }

  return (
    <div className='text-input--container'>
        <label className='label'>
            Setup:
        <textarea type='text'
            placeholder='Meme Setup'
            onChange={(event) => andleTopText(event)}
        />
        <input type='color'
            onChange={(event) => andleTopColor(event)}
        />
        <button
            onClick={() => andleMoreClick('top')}
        >More</button>
        {/* Code With Problem */}
        {(memeText.status.top.isMoreOn) && <p>more is on</p>}
        </label>
        <label className='label'>
            Punchline:
        <textarea type='text'
            placeholder='Meme Punchline'
            onChange={(event) => andleBottomText(event)}
        />
        
        <input type='color'
            onChange={(event) => andleBottomColor(event)}
            className='red'
        />
        </label>
        <button 
            onClick={andleSaveMeme}
        >Save in gallery</button>
        
    </div>
  )
}

export default TextInput

Any help would be greatly appreciated! I’m looking for suggestions on how to resolve the issues with props or if there are common mistakes I might have overlooked. Thank you!

React Props Issue: Red Underscores and Unexpected Behavior

Hi everyone!

Recently, I have been working on a Meme Project with ReactJs as the Frontend. It is basically a simple app that lets users make memes fast and effectively. Until, I woke up yesterday with a very weird problem. VS Code indicates that there is a problem with using Props in the Components. Which, I have been trying to resolve since yesterday Unfurtunately, It’s decreasing my productivity.
Even AI could not handle the problem.

Problem 1: Props in all Components have red lines under them.

  • Example line: Line 12 in Oome Component
  • function Oome ({savedMemes, setSavedMemes}) {...}

Problem 2: Props are not working as expected and have red line under each.

  • Example line: Line 106 in TextInput Component
  • {(memeText.status.top.isMoreOn) && <p>more is on</p>}

Note: Typos in the code are intentional. Because my keyboard has missing letters. 🙂

Debugging Attempts:

  • Using Props: I used the instead of calling the property directly
  • Simplifying: I simplify the code. Hopping that the problem comes from its complication.

Unfortunatly, both ways did not change in the problem.

Code below has {/* Code With Problem */} over the lines mentioned under each previous problem in the post.

Current Code:

  • App Component:
import{ useEffect, useState } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from "./Pages/Home/Oome";
import UserMemes from "./Pages/UserMemes/UserMemes";

const App = () => {
  const {savedMemes, setSavedMemes } = useState([]);

  useEffect(() => {
    console.log(savedMemes)
  }, [savedMemes])

  return (
    <Router>
      <Routes>
        <Route
          path="/"
          element={
            <Home savedMemes={savedMemes} setSavedMemes={setSavedMemes}
              
            />
          }
        />
        <Route path="/jallary" element={<UserMemes savedMemes={savedMemes} setSavedMemes={setSavedMemes} />} />
      </Routes>
    </Router>
  );
};

export default App;

  • Oome Component:
import { useEffect, useState , useRef} from "react";
import "./Oome.css";
import Navbar from "../../Components/NavBar/Navbar";
import BottomeNavBar from "../../Components/BottomNavBar/BottomNavBar";
import Preview from "../../Components/Preview/Preview";
import TextInput from "../../Components/TextInput/TextInput";

import html2canvas from "html2canvas";
import { Download } from "../../Components/Download/Download";
import { GetMemeButton } from "../../Components/GetMemeButton/GetMemeButton";

{/* Code With Problem */}
function Oome ({savedMemes, setSavedMemes}) {
  const [selectedFile, setSelectedFile] = useState(``);
  const imeRef = useRef()

  function andleDownload() {
    html2canvas(imeRef.current, { useCORS: true }).then((canvas) => {
        const link = document.createElement("a");
        link.href = canvas.toDataURL("image/png");
        link.download = "download.png";
        link.click();
      });
  }

  const [memeText, setMemeText] = useState({
    top: {
      topText: ``,
      color: ``,
    },
    bottom: {
      bottomText: ``,
      color: ``,
    },
    imae: {
        data: null,
      },
    status : {
        date: null,
        top: {
          isMoreOn: false
        },
        bottom: {
          isMoreOn: false
        }
    }
  });

 

  useEffect(() => {
    if (selectedFile) {
      setMemeText((prevMemeText) => ({
        ...prevMemeText,
        imae: {
          data: selectedFile,
        },
        status : {
            date: new Date().getHours(),
            
            top: {
              isMoreOn: false,
            },
            bottom: {
              isMoreOn: false,
            }
        }
      }));
    }
    // savedMemes()
  }, [selectedFile]);

  
  return (
    <div className="oome-container">
      <Navbar setSelectedFile={setSelectedFile} />
      <Preview 
        selectedFile={selectedFile} 
        memeText={memeText}
        savedMemes={savedMemes}
        imeRef={imeRef}
      />
      <TextInput
        memeText={memeText}
        setMemeText={setMemeText}
        setSavedMemes={setSavedMemes}
        savedMemes={savedMemes}
        andleDownload={andleDownload}
      />
      
        <Download andleDownload={andleDownload}/>
        <GetMemeButton />
      <BottomeNavBar />
    </div>
  );
};

export default Oome;
  • TextInput Component:
import { useState } from 'react';
import './TextInput.css';

const TextInput = ({setMemeText, memeText, setSavedMemes, savedMemes}) => {
    
    

    function andleTopText(event) {
        const topText = event.target.value
        console.log(topText)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                top : {
                    ...prevMemeText.top,
                    topText: topText,
                }
                
            }
        ))
    }
    function andleTopColor(event) {
        const topColor = event.target.value
        console.log(topColor)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                top : {
                    ...prevMemeText.top,
                    color: topColor
                }
                
            }
        ))
    }
    function andleBottomText(event) {
        const bottomText = event.target.value
        console.log(bottomText)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                bottom : {
                    ...prevMemeText.top,
                    bottomText:bottomText
                }
                
            }
        ))
    }

    function andleBottomColor(event) {
        const bottomColor = event.target.value
        console.log(bottomColor)
        
        setMemeText(prevMemeText => (
            {
                ...prevMemeText,
                bottom : {
                    ...prevMemeText.top,
                    color: bottomColor 
                }
                
            }
        ))
    }

    function andleSaveMeme() {
        setSavedMemes(prevSavedMemes => ([
            ...prevSavedMemes,
            memeText
        ]))
        console.log(`savedMemes: `, savedMemes)
    }

    const [isMoreOn, setIsMoreOn] = useState(false)

    function andleMoreClick(position) {
        setIsMoreOn((prev) => !prev)
        setMemeText((prev) => ({
            ...prev,
            status: {
                ...status,
                [position]: isMoreOn
            }
        }) 
        )
    }

  return (
    <div className='text-input--container'>
        <label className='label'>
            Setup:
        <textarea type='text'
            placeholder='Meme Setup'
            onChange={(event) => andleTopText(event)}
        />
        <input type='color'
            onChange={(event) => andleTopColor(event)}
        />
        <button
            onClick={() => andleMoreClick('top')}
        >More</button>
        {/* Code With Problem */}
        {(memeText.status.top.isMoreOn) && <p>more is on</p>}
        </label>
        <label className='label'>
            Punchline:
        <textarea type='text'
            placeholder='Meme Punchline'
            onChange={(event) => andleBottomText(event)}
        />
        
        <input type='color'
            onChange={(event) => andleBottomColor(event)}
            className='red'
        />
        </label>
        <button 
            onClick={andleSaveMeme}
        >Save in gallery</button>
        
    </div>
  )
}

export default TextInput

Any help would be greatly appreciated! I’m looking for suggestions on how to resolve the issues with props or if there are common mistakes I might have overlooked. Thank you!

How to dynamically import js modules in react typescript hosted on external URLs?

I have module hosted on external weburl

//  www.xyz.com/order.js
export function order() {
  const create = () => {
    console.log('Order created');
  };
  return { create };
}

I want to load this module dynamically in react typescript. I tried using

let module:any;
let configUrl = "www.xyz.com/order.js";
if(selectedModule === 'order'){
module = await import(/* webpackIgnore: true */ configUrl);
      console.log("module",module.create())
}

However this throws error

Unexpected token 'export'
SyntaxError: Unexpected token 'export'

How to dynamically import js modules in react typescript hosted on external URLs?

I have module hosted on external weburl

//  www.xyz.com/order.js
export function order() {
  const create = () => {
    console.log('Order created');
  };
  return { create };
}

I want to load this module dynamically in react typescript. I tried using

let module:any;
let configUrl = "www.xyz.com/order.js";
if(selectedModule === 'order'){
module = await import(/* webpackIgnore: true */ configUrl);
      console.log("module",module.create())
}

However this throws error

Unexpected token 'export'
SyntaxError: Unexpected token 'export'

OpenApi Generator generated API messes up TimeZones

I am trying to generate the Frontend and Backend API using the OpenAPI generator. In my schema I have the following object:

Range:
  type: object
  properties:
    creationDate:
      type: string
      format: date
    from:
      type: string
      format: date-time
    to:
      type: string
      format: date-time

For the backend I use following typeMappings in my gradle file to make my Model use LocalDateTime instead of OffsetDateTime:

typeMappings = ['string+date-time': 'LocalDateTime']
importMappings = ['LocalDateTime': 'java.time.LocalDateTime']

Now the generated model for my backend looks like this:

@Valid
private LocalDate creationDate;

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime from;

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime to;

The frontend simply uses Date for both types. It is executed simply using:

openapi-generator-cli generate

The problem I am now facing is, that the Dates and Times that I get out of a form in my frontend have timezone information (GMT+2) attached to them. When being passed into the backend, the generated frontend code calls the following method:

'from': value['from'] == null ? undefined : ((value['from']).toISOString()),

This leads to the time being set back by 2 hours since the GM+2 indicates a 2 hour time difference.
However in the backend the date I get is treated with the value it receives (so with 2 hours prior) but as GMT+2. Which means that the value in the backend is actually saved as 2 hours earlier than what has been put in.
The same applies to the date, which in this case leads to the date being saves as a day earlier.

I am at a loss of what I am doing wrong or how I could solve this without manually kicking over the timezone in the data I pass into the generated service.

How to Fix this [closed]

der.
PS C:UsersHPOneDriveDesktopResume Builderinteractive-resume-builder> npm start

[email protected] start
react-scripts start

There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix locally.

The react-scripts package provided by Create React App requires a dependency:

“eslint”: “^6.6.0”

Don’t try to install it manually: your package manager does it automatically.
However, a different version of eslint was detected higher up in the tree:

C:UsersHPOneDriveDesktopResume Builderinteractive-resume-buildernode_moduleseslint (version: 9.12.0)

Manually installing incompatible versions is known to cause hard-to-debug issues.

If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That will permanently disable this message but you might encounter other issues.

To fix the dependency tree, try following the steps below in the exact order:

  1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.
  2. Delete node_modules in your project folder.
  3. Remove “eslint” from dependencies and/or devDependencies in the package.json file in your project folder.
  4. Run npm install or yarn, depending on the package manager you use.

In most cases, this should be enough to fix the problem.
If this has not helped, there are a few other things you can try:

  1. If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead.
    This may help because npm has known issues with package hoisting which may get resolved in future versions.

  2. Check if C:UsersHPOneDriveDesktopResume Builderinteractive-resume-buildernode_moduleseslint is outside your project directory.
    For example, you might have accidentally installed something in your home folder.

  3. Try running npm ls eslint in your project folder.
    This will tell you which other package (apart from the expected react-scripts) installed eslint.

If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That would permanently disable this preflight check in case you want to proceed anyway.

P.S. We know this message is long but please read the steps above 🙂 We hope you find them helpful!

Solution to fix problem am facing