Not able to see image after adding display flex. Image got shrinken

I am creating a page in React which left side of page contains image with Carousel and right side has its information.
Before display:flex the images are visible but after adding display:flex, the image got shrinken and dots of Carousel is visible like this:
enter image description here

Product.jsx:

import React, { Fragment, useEffect } from 'react'
import Carousel from 'react-material-ui-carousel';
import "./ProductDetails.css";
import { useSelector,useDispatch } from 'react-redux';
import { getProductDetails } from '../../actions/productAction';
import { useParams } from 'react-router-dom';

const ProductDetails = () => {
  const {id}=useParams();
  const dispatch=useDispatch()  ; 
  const {product,loading,error}=useSelector((state)=>state.productDetails);
  useEffect(()=>{
    dispatch(getProductDetails(id));
  },[dispatch,id])
  return (
    <Fragment>
          <div className="ProductDetails">
            <div>
              <Carousel>
                {product.image &&
                  product.image.map((item, i) => (
                    <img
                      className="CarouselImage"
                      key={item.url}
                      src={item.url}
                      alt={`${i} Slide`}
                    />
                  ))}
               </Carousel>
            </div>
          </div>

    </Fragment>
  )
}
export default ProductDetails;

css is:

.ProductDetails{
    width: 100vw;
    max-width: 100%;
    padding: 6vmax;
    box-sizing: border-box;
    display: flex;
}

Google Maps API: Multiple markers placed on map from user input

I’m developing a React site and I want to incorporate the Google Maps API to display bars associated with specific football clubs on a map. Essentially, I would like users to input a country and a football club, and the site should show markers or pins on the map indicating the locations of bars associated with that club in the selected country.

I have already set up the basic structure of my React site and have successfully integrated the Google Maps API to display a default map. However, I’m unsure about how to proceed with the dynamic display of bars based on user input.

Here’s an overview of my current setup:

I have the MapComponent.jsx file:

import { GoogleMap, Marker } from "@react-google-maps/api";


// Array of bar data with country, football club, and coordinates
const bars = [
  { country: 'Australia', club: 'Arsenal', lat: -33.885055433597, lng: 151.20966156719123 },
  { country: 'Australia', club: 'Manchester United', lat: -34.94636965495918, lng: 138.62657079153266 },
  { country: 'Canada', club: 'Liverpool', lat: 49.28637807745695, lng: -123.11695651719553 },
  { country: 'Germany', club: 'Bayern Munich', lat: 48.175002206190136, lng: 11.592748746031473 },
  { country: 'Japan', club: 'Manchester United', lat: 53.4631, lng: -2.2913 },
  { country: 'Japan', club: 'Liverpool', lat: 35.64857860594483, lng: 139.71303475978445 },
  { country: 'South Korea', club: 'Manchester United', lat: 53.4631, lng: -2.2913 },
  { country: 'South Korea', club: 'Tottenham Hotspurs', lat: 37.552079094148446, lng: 126.9226752350085 },
  { country: 'South Korea', club: 'Liverpool', lat: 37.56004882603966, lng: 126.92511388465444 },
  { country: 'United States', club: 'Arsenal', lat: 40.74496672417892, lng: -73.99249257407631 },
  { country: 'United States', club: 'Arsenal', lat: 32.74202567965132, lng:  -117.1289996550291 },
  { country: 'United States', club: 'Liverpool', lat: 34.007969428759544, lng: -118.41245218835955 },
  { country: 'United States', club: 'Manchester United', lat: 39.750624531403766, lng: -104.9853437709032 },

  // Add more bar data as needed
];

const mapOptions = {
  mapId: "cb21e6acbb31cd1",
  scrollwheel: true, // Enable scroll wheel zooming
  minZoom: 2,
  maxZoom: 20
  
};

function MapComponent({ center, zoom }) {
    
  return (
    <GoogleMap
      mapContainerStyle={{ width: "75%", height: "600px", margin: "0 auto" }}
      mapTypeId=""
      center={center}
      zoom={zoom}
      options={mapOptions}
    >
      {/* Render markers here */}
    </GoogleMap>
  );
}

export default MapComponent;

and I have a Map.jsx file:

import React, { useState } from "react";
import NavBar from "./NavBar";
import Image from "../Haaland.png";
import MapComponent from "./MapComponent";
import { LoadScript } from "@react-google-maps/api";
import Footer from "./Footer";
import CountryAutoComplete from "./CountryAutoComplete";
import ClubAutocomplete from "./ClubAutoComplete";

function Map() {
  // Set initial center and zoom level
  const center = { lat: 0, lng: 0 };
  const zoom = 3;

  return (
    <>
      <NavBar />

      <section id="InputSection">
        <div className="InputDiv">
          <h1 className="MapPageHeaderText">Type in your Location and Club</h1>

          <div className="CountryDiv">
            <i
              class="fa-solid fa-earth-europe"
              style={{
                color: "white",
                fontSize: "xx-large",
                marginBottom: "15px",
                marginRight: "10px",
              }}
            ></i>

            <CountryAutoComplete
              suggestions={[
                "Australia",
                "Belgium",
                "Canada",
                "England",
                "France",
                "Germany",
                "Ireland",
                "Italy",
                "Japan",
                "Spain",
                "South Korea",
                "Sweden",
                "United States of America",
              ]}
            />
          </div>

          <div className="ClubDiv">
            <i
              class="fa-regular fa-futbol"
              style={{
                color: "white",
                fontSize: "xx-large",
                marginBottom: "15px",
                marginRight: "10px",
              }}
            ></i>

            <ClubAutocomplete
              suggestions={[
                "Arsenal",
                "AC Milan",
                "Barcelona FC",
                "Bayern Munich",
                "Chelsea",
                "Juventus",
                "Manchester City",
                "Manchester United",
                "Liverpool",
                "Real Madrid",
                "Tottenham",
                "West Ham United",
              ]}
            />
          </div>

          <button
            type="submit"
            className="SearchButton"
            style={{ width: "300px", height: "50px" }}
          >
            Search
          </button>
        </div>

        <div className="ImageDiv">
          <img
            className="PlayerImage2"
            src={Image}
            alt="Erling Haaland holding Premier League Trophy"
          />
        </div>
      </section>

      <div className="MapSection">
        <h1 className="MapDivText">Results</h1>
        <LoadScript googleMapsApiKey="AIzaSyC5TQRQXVpsBHskHxxifLJfl9w53tp4hqo">
          <div
            style={{
              marginLeft: "auto",
              marginRight: "auto",
              marginTop: "50px",
            }}
          >
            <MapComponent center={center} zoom={zoom} />
          </div>
        </LoadScript>

        <a href="/map">
          <button className="ResetButton">Reset</button>
        </a>
      </div>

      <Footer />
    </>
  );
}

export default Map;

Any pointers in the right direction are appreciated.

Update state dynamically with target.id, target.name and target.value?

I have multiple groups of input boxes, for entering a carrier (carrierName) and another for shipping ID (trackingId), for each order (each with an orderId), on one page. The page is a summary page of all orders. Each group of carrier and shipping ID fields have an adjacent ‘ship’ button, to send the data to the database and update the order status.

I understand that I can use dynamic inputs in React like this:

 setInputs((prev) => {
  return { ...prev, [e.target.name]: e.target.value };
});

but this means I cannot determine which orderId to update, as there could be lots of input boxes, for lots of orders, updated with text on this single page.

I am looking for advice on how to add another field to the setState function, like e.target.id, for example, to be able to determine which orderId to update the carrier and tracking id for. I have tried this:

setInputs((prev) => {
      return { ...prev, [e.target.id]: { [e.target.name]: e.target.value } };

but this just replaces the carrierName with the trackingId, if the user updates the tracking Id text box, after updating the carrierName text box.

I have also tried this:

setInputs((prev) => {
  return { ...prev, [e.target.id]: { ...prev, [e.target.name]: e.target.value } };
});

but it gives me a heavily duplicated object, with the id listed loads of times and then the carrier name also listed many times, for each keystroke I make:

{"649dca0bda67f0b32c6d8224":{"649dca0bda67f0b32c6d8224":{"649dca0bda67f0b32c6d8224":{"649dca0bda67f0b32c6d8224":{"649dca0bda67f0b32c6d8224":{"649dca0bda67f0b32c6d8224":{"carrierName":"u"},"carrierName":"up"},"carrierName":"ups"},"trackingId":"1"},"trackingId":"12"},"trackingId":"123"}}

I would like the inputs state variable to look like this:

{orderId: 649dca0bda67f0b32c6d8224, shipData: ["carrierName":"UPS","trackingId":"123"]},
{orderId: 649dca0bda67f0b32c6d8224, shipData: ["carrierName":"UPS","trackingId":"49204"]},

Is this possible with a single dynamic setInputs function, like the above?

Do I need to add @types/* in devDependencies? [duplicate]

Actually I read a lot of answers about it. I understand that some people think that @types/* should be in ‘dependencies’ because nobody want to install all devDependencies manually, but in works if someone going to download your project. I want to know how it works with big project. For example there is a big website (frontend: react+typescript) is being developed by the team. Where are they add @types/*? I guess in ‘devDependencies’ because typescript use only in development and then converts in javascript, so types needn’t to be in ‘dependencies’. Tell me if I’m wrong, I really want to figure it out.

How to decode a KTX2 texture using KTX2Decoder from Babylon.js

I want to decode a texture in .ktx2 format and then convert it to .png in Node.js. I tried using the KTX2Decoder from Babylon.js, but I haven’t had any success.

This is what I’m doing:

const ktx2decoder = require("babylonjs-ktx2decoder");
const fs = require('fs');

const data = fs.readFileSync("./image.ktx2");

const a = new ktx2decoder.KTX2Decoder();
a.decode(data, {
  astc: false,
  bptc: true,
  s3tc: true,
  pvrtc: false,
  etc2: false,
  etc1: false,
}).then(b => console.log(b))

And this is what I’m getting:

{
  width: 4096,
  height: 4096,
  transcodedFormat: 36492,
  mipmaps: [ { data: null, width: 4096, height: 4096 } ],
  isInGammaSpace: true,
  hasAlpha: true,
  transcoderName: 'MSCTranscoder',
  errors: 'ReferenceError: importScripts is not definedn' +
    'ReferenceError: importScripts is not definedn' +
    '    at C:\Users\canor\Desktop\ktx\node_modules\babylonjs ktx2decoder\babylon.ktx2Decoder.js:1:14029n' +
    '    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)n' +
    '    at async Promise.all (index 0)n'
}

I’m not sure what I’m doing wrong. I appreciate any help.

Vue3 Set List Item Different for Every Loop

I have a panel that I looping through.

<component
  :list="levels"
  @chosen="activeLevel++"
  @configData="configData"
  :active-level="activeLevel"
  :is="BaseLevel"
></component>

Everytime user clicks to one item ım changing component with levels[activeLevel]

Hovewer, I want to set item’s text to different values per loop

so lets say first user will choose gender

let userGender = choosenItem[0]

let userAge = choosenItem[1]

and realistic code is something like this:

in child :

emitEvent('configData', item.text )

in parent:

@configData="configData"

let configurations = ref({ gender: null, fitLevel: null, height: null })

function configData(text) {
  configurations[activeLevel].value = text;

  console.table(configurations.value)
}

and then ı want to make a formula with these informations but ı dont know its relevant

not: please add comments if you want any more code detail. I didn’t send the actual code because I didn’t want to pollute the post

I have a problem with the marquee Effect. Adding a margin when it goes off-screen affects other elements in marquee

I apologize if my question seems silly, but I have been trying hard to solve this problem with an HTML unordered list that includes a marquee element. Using JavaScript, I have set it up to display details when hovering over an <a> tag, but since the marquee is continuously moving, only half of the details appear when part of the text is off-screen. I tried to fix this by using a for loop to detect when the section goes off-screen and add a margin, but it causes issues with the second marquee. Even when it’s fully on-screen and I hover over it, it still takes a margin.

I tried deleting the second marquee tried using for loop

const details = document.querySelectorAll('.details');
setInterval(() => {
  details.forEach((detail) => {
    const detailPosition = detail.getBoundingClientRect();

    if (detailPosition.left <= -50) {
      detail.style.marginLeft = "30rem";
    }

  });
}, 1);
<div class="marquee">
  <ul class="marquee__content">
    <li>
      <div class="link-container">
        <a>Oblon Firm and Attorneys Recognized by IP STARS from Managing IP</a>
        <div class="details">
          <h2>FIRM NEWS </h2>
          <p>Founder, Norman Oblon, Named an Intellectual Property Trailblazer by The National Law Journal</p>
          <button>More+</button>
        </div>
      </div>
    </li>
    <li>
      <div class="link-container">
        <a>Oblon and Firm's Attorneys Highly Ranked in 2023 IAM Patent 1000</a>
        <div class="details">
          <h2>ARTICLE </h2>
          <p> Show Me the Money – USPTO Fee Proposals Include Fee Provisions to Impact Applicant Behavior </p>
          <button>More+</button>


        </div>
    </li>
    <li>
      <div class="link-container">
        <a>CAFC Addresses Requirements for Award of Attorneys' Fees</a>
        <div class="details">
          <h2>ARTICLE </h2>
          <p> CAFC Addresses Requirements for Award of Attorneys' Fees </p>
          <button>More+</button>
        </div>


      </div>
    </li>
  </ul>
  <!-- Mirrors the content above -->
  <ul class="marquee__content">
    <li>
      <div class="link-container">
        <a>Oblon Firm and Attorneys Recognized by IP STARS from Managing IP</a>
        <div class="details">
          <h2>FIRM NEWS </h2>
          <p>Founder, Norman Oblon, Named an Intellectual Property Trailblazer by The National Law Journal</p>
          <button>More+</button>
        </div>
      </div>
    </li>
    <li>
      <div class="link-container">
        <a>Oblon and Firm's Attorneys Highly Ranked in 2023 IAM Patent 1000</a>
        <div class="details">
          <h2>ARTICLE </h2>
          <p> Show Me the Money – USPTO Fee Proposals Include Fee Provisions to Impact Applicant Behavior </p>
          <button>More+</button>


        </div>
    </li>
    <li>
      <div class="link-container">
        <a>CAFC Addresses Requirements for Award of Attorneys' Fees</a>
        <div class="details">
          <h2>ARTICLE </h2>
          <p> CAFC Addresses Requirements for Award of Attorneys' Fees </p>
          <button>More+</button>
        </div>


      </div>
    </li>
  </ul>
  </div>

can I use both React and plain Javascript?

I want to build a website using React and Stacks Design. For example, to open and hide Dropdown Menu or Tooltip we can put proper data attributes on the button and then Stacks.js do the rest. I know that in React we can use hooks for this so the question is whether using pain javascript to do it doesnt contradict with the idea behind react? It works but I’m pretty new in React and I would like to know whether I dont do something what is prohibited in React

Tooltip not showing on d3.js area graph

I’m trying to show a tooltip when hovering over my d3.js area graph. I’m not seeing the tooltip appear.

I’ve looked at the mousemove event and mouseout and it looks correct. Not sure where I’m going wrong.

Link to JS fiddle: https://jsfiddle.net/j2vk8txh/

                source.selectAll(".area")
                .style("opacity", 1) // Set the initial opacity to 1
                .style("stroke", "none") // Add a stroke
                .on("mousemove", function (d) {
                    var x0 = x.invert(d3.mouse(this)[0]);
                    var bisect = d3.bisector(function (d) { return d.date; }).left;
                    var i = bisect(d.values, x0, 1);
                    var d0 = d.values[i - 1];
                    var d1 = d.values[i];
                    var d = x0 - d0.date > d1.date - x0 ? d1 : d0;

                    d3.select(this)
                        .transition()
                        .duration(50)
                        .style("opacity", 0.85);

                    // Show tooltip
                    tooltip.transition().duration(200).style("opacity", 0.9);
                    tooltip.html("X: " + d3.timeFormat("%Y-%m-%d")(d.date) + "<br/>Y: " + d.kW)
                        .style("left", (d3.event.pageX + 10) + "px")
                        .style("top", (d3.event.pageY - 28) + "px");
                })
                .on("mouseout", function (d) {
                    d3.select(this)
                        .transition()
                        .duration(50)
                        .style("opacity", 1);

                    // Hide tooltip
                    tooltip.transition().duration(500).style("opacity", 0);
                });

How to filter objects in an array with multiple of the same values

I am attempting to make a discord bot using discord.js (unrelated to this question) however when I tried to list the staff infractions that one user has, I keep getting all values returned as undefined. It works perfectly when a user has 1 infraction, but more than 1 returns undefined.

In my JSON File labeled “infractions.json”

[
  {
    "user": "1387128937182739182",
    "reason": "test",
    "punishment": "banned"
  },
  {
    "user": "648314224174432267",
    "reason": "Bad",
    "punishment": "bad"
  },
  {
    "user": "648314224174432267",
    "reason": "testing bot",
    "punishment": "lmao"
  }
]

And in my js file

var id = //the inputted id
var myArray = fs.readFileSync("infractions.json");
var arr = JSON.parse(myArray)

let obj = arr.filter(o => o.user === id);


console.log(obj)

Logging the obj variable results in this in the console

[
  {
    "user": "648314224174432267",
    "reason": "Bad",
    "punishment": "bad"
  },
  {
    "user": "648314224174432267",
    "reason": "testing bot",
    "punishment": "lmao"
  }
]

However when I use obj.user, obj.reason, or obj.punishment it returns undefined.

If there is only one object where user is 648314224174432267 It works perfectly and the reason and punishment are listed.

If anyone can help it would be greatly appreciated!

Javascript drag and drop added to class objects

Is there a way to get every object instance of a class to be draggable? So far I have this:

class RoomObjects {
  constructor(game) {
    this.game = game;
    this.image = document.getElementById("r108_Items"); //draggable
    this.image.addEventListener('dragstart', this.dragStart);
  }
  dragStart(e) {
    console.log('drag happened:' + e.target);
  }
}

const myRO = new RoomObjects("fooGame");
#r108_Items {
  display: inline-block;
  padding: 3rem;
  background: red;
}
  <div id="r108_Items" draggable="true">Drag me</div>

But when the object is instantiated in the game class I don’t see any updates on the console indicating that the drag was successful.

How to restore data after refreshing component

Currently I’m writing an application in which there is a table and a detail page accessed by route element. I do use the params element to select required detail, the page displays without the problem and the data of selected element is presented. My problem is that after reload the store state isn’t loaded as fast as component is and the mapping of the page is gone. What should I do to persist the state of my user details component after reloading the page. I would like not to use the localstorage neither another library.

<Route path="/table/:userId" element={<Details />} />

<td>
                                    <button>
                                        <Link to={`/table/${user.id}`}>
                                            Details
                                        </Link>
                                    </button>
                                </td>

const Details = (props) => {
    const {userId} = useParams()

    console.log(props)
     console.log(userId)

   const user = useSelector((state) => state.users.data.find((u) => u.id === Number(userId)))
   
    return (
        <>
            <div className="css">
                <div className="css">
                    <h2>Some details</h2>
                    <p>Name: {detail.name}</p>
                    <p>Email: {detail.email}</p>
                    <p>City: {detail.city}</p>
                    <p>Country: {detail.country}</p>
                </div>
            </div>
        </>
    )
}

function mapStateToProps (state) {
    return {
        data: state.users.data,
        error: state.users.error
    }}

export default connect(mapStateToProps)(Details)

export const fetchUsers = createAsyncThunk('table/fetchUsers', async () => {
    const data = await fetcher('http://localhost:3001/users/')
    return data
})

I’ m trying to fetch the data once more in useEffect element but there is still error that Cannot read properties of undefined (reading 'name'). It’s my first try, the other was to try mapDispatch ToProps method but it still failed.

In react , addEventListner does not work properly with useEffect

I have used a div and click eventListner on it. My intention is to log value of count after each increment.
But it is not happening

import React, { useEffect, useRef, useState } from 'react'

export default function LOL() {

    const [count,setCount] = useState(0);
    const divRef = useRef(null);

    const handleCount = () =>{
        setCount(prev=>prev+1);
    }

    // Add event Listner to the div
    useEffect(()=>{
        const div = divRef.current;

        const handleCount2 = () =>{
            setCount(prev=>prev+1);
        }

        div.addEventListener('click', handleCount);
        return(
            div.removeEventListener('click', handleCount)
        );
    },[])
    // Print value of count after each change
    useEffect(()=>{
        console.log(count);
    },[count])

  return (
    <div ref = {divRef} style={
        {
            width:'500px', height:'500px',backgroundColor:'black'
        }
    }>

    </div>
  )
}

  • If I use code as it is , it will print only zero (in both function hadleCount and handleCount2) it wont work, dont know why
  • If i make removeEventListner disappear it works perfectly for handleCount but for handleCount 2 it will print 2 times each with increment( like instead of 1 it will be 1 2)
  • if i make Event Listner useEffect run every time it behave like above but on staroid

I know i should not be using DOM element in react but addEventListner are sometime required in special cases

What causes the failure of this return statement inside a React 18 template?

I have been working on an SPA with React 18 and The Movie Database (TMDB) API.

I have a component intended to display movie trailers, that I use on the movie details page like this:

{trailers.length ?
  <>
    <div className="mb-3">
      <h2 className="section-title">Trailers</h2>
      <TrailerCarousel trailers={trailers} />
    </div>
  </> : <></>
}

In the Trailercarousel.jsx file I have:

import './Trailercarousel.css';

function Trailercarousel({ trailers }) {
  return (
    <div id="trailersCarousel" className="carousel slide" data-bs-interval="false">
      {trailers.length > 1 ?
        <>
          <ol className="carousel-indicators">
            return trailers.slice(0, maxCarouselItems).map((video, index) => (
              <li
                key="video.id"
                data-bs-target="#trailersCarousel"
                data-bs-slide-to="`${index}`"
                className="{ active: index === 0 }"
              >
                {index + 1}
              </li>
            ));
          </ol>
        </> : <></>
      }

      <div className="carousel-inner">
        return trailers.slice(0, 5).map((video, index) => (
          <div
            v-for="(video, index) in trailers.slice(0, maxCarouselItems)"
            key="video.id"
            className="carousel-item"
            activeclassname="{ active: index === 0 }"
          >
            <iframe
              className="embed-responsive-item"
              src="`https://www.youtube.com/embed/${video.key}`"
            ></iframe>
          </div>
        ));
      </div>
    </div>
  );
}

export default Trailercarousel;

The problem

The expression below does not return the <li> elements:

return trailers.slice(0, maxCarouselItems).map((video, index) => (
  <li
    key="video.id"
    data-bs-target="#trailersCarousel"
    data-bs-slide-to="`${index}`"
    className="{ active: index === 0 }"
  >
    {index + 1}
  </li>
));

Instead, return trailers.slice(0, maxCarouselItems).map((video, index) => (...)); is displayed, as if it ware a string.

Why does the return statement fail in this case?