React component with re usable avatar

I’m new to React and have hit a roadblock. Basically, I’m trying to create a simple reusable component. I am using MUI and want to create an avatar component to be called anywhere with a different image for when it is called. I want to be able to call in an argument when declaring the component in various pages. Please help

import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Stack from '@mui/material/Stack';
import frankieAvatar from '/Users/rodriguezmedia/Desktop/react-counter-app/src/images/oink.png';
import { AvatarGroup } from '@mui/material';

const designerOne = {
    src: frankieAvatar
}

export default function AvatarDesigners() {
    return (
        <Avatar src={designerOne.src}></Avatar>
    );
}

Mobile nav flashed/blinks on open

Link to site

When opening the nav menu on the above site there is sometimes a flash/blink of the orange menu that slides in from the right. It doesn’t happen every time and I’m only seeing the issue on mobile devices. It works fine on desktop browsers and I’m not seeing the issue in Chrome dev when I toggle device toolbar.

Troubleshooting thus far:

  • I’ve tried changing z-index for items in the navbar but haven’t had any luck.
  • I copy/pasted the code for navbar only to a new project and did not see the same problem on my mobile device.
  • Problem occurs on Safari and Chrome mobile browsers.

My thought is that there is a conflict between z-index in mobile navbar and z-index on page somewhere but I’m not quite sure. Interested to hear if anyone has thoughts on what it could be and how to best direct my troubleshooting.

this site was built in Webflow but I have decent understanding of HTML/CSS/JS.

Thank you!

Laravel 9: Where to place common javascript file?

In my Laravel 9 project that I am working on, I want to put a javascript file containing common functions in app.blade.php. As per How to include External CSS and JS file in Laravel 5.5, I placed the js file in public/js folder and included the following in app.blade.php

 <!-- common js functions added by Ravi  -->
<script src="{{ asset('js/common_js.js') }}" ></script>

However, this file is not getting included on the page, and the js functions included in the file are not available in console.

Could someone advise me how to include a js file so that it is available for all pages?

Thanks.

How to display the values from a map on a react web app (javascript)

I am new to JavaScript. I have a map in which I store 3 values to each key. The size of the map is variable and a new key:values pair is added every time a new item is published on the app.

I would like to display the current contents of the map on the web page (ideally a table format but for now I just want to see them printed there before I worry about that). All my searches are obstructed by people talking about google maps.

I have found ways to solve this when using an array but I like the structure of the map.

I initialize an empty map:

const productMap = new Map();

New items are added to the site and the map expanded:

    handleSubmit = async () => {
    const { cost, itemName, quantity } = this.state;

    let result = await this.ItemManager.methods.createItem(itemName, cost, quantity).send({ from: this.accounts[0] });
    const index = result.events.ProductStep.returnValues._productIndex;

    productMap.set(index, {itemName: itemName, cost: cost, quantity: quantity}); **// This is where map values are added. 1 key (index) has 3 values (itemName, cost and quantity)**

    console.log(productMap)
    
    alert("Send "+cost+" Wei to "+result.events.ProductStep.returnValues._address);
  };

This function prints to the console exactly how I want, but I am not sure how to get this into the JSX (I think that’s the right term?) part.

    printValues = () => {
    for(let [key, value] of productMap){
      console.log(value.itemName +':'+ value.cost +':'+ value.quantity) **//This logs 'Item Name' : 'cost' : 'quantity' in a separate row for each key- this is what I ideally want but displayed on the web page**

      return(
        <div>{value.itemName} {value.cost} {value.quantity}</div>
        )
    }
   }

I have tried many variations to get this to show up on the web page, but nothing has worked so far.

 return (
      <div className="App">
        <header className='App-header' ><img className='App-logo' src={mylogo} alt="logo"/></header>
        <h1>Simply Payment/Supply Chain Example!</h1>
        <h2>Products for sale:</h2>

        {this.printValues} **//I imagine it being something along these lines where the
 //function produces the desired values and they are displayed on the web page.**

Thank you for any help!

(Beginner)How can I make this code faster where I have to print the total off ods of a given number?

I am really new at coding, and I was able to solve this problem with what I know right now.
The problem is: Print out how much odd numbers there are in a given number.

    function oddCount(n){
  var odd=[];
 for(i=0;i<n;i++){
   if(i%2==1){
   odd.push([i]);
   }
 }
  return odd.length;
}
function oddCount(8);

As we can see, it works properly, however, on codewars, it wants me to optimize it to run faster. Can someone show me how so I can learn it quickly please.

Debounced change handler in React won’t change input if value is defined

I’m coding a simple Reddit client in JavaScript using React, and I have an element in my header that changes the subreddit to be displayed – with the Lodash debounce applied inside of the React useMemo hook to prevent excessive handleChange calls while typing.

However, when the value prop of the input element is set to the appropriate useState variable, the input becomes impossible to alter.

This is the code that works, albeit with limitations I’m hoping to overcome:

import React, { useMemo } from 'react';
import debounce from 'lodash.debounce';

export const Header = ({ subreddit, setSubreddit }) => {
  const handleChange = ({ target }) => {
    setSubreddit(target.value)
  }
  
  const debouncedHandleChange = useMemo(() => {
    return debounce(handleChange, 500)
  }, [])

  return (
    Superliminal/ <input type='text' onChange={debouncedHandleChange} placeholder={subreddit} autofocus/>
  )
}

Things get problematic when you define the value prop of the input element like so:
value={subreddit}

Currently, I don’t understand why this causes the input to become inalterable, and I would prefer it to be the case that the value, and not just the placeholder, remains equal to the subreddit state variable. I especially don’t understand because without the debounce implementation, you can define value as the state variable without issues.

If it’s necessary, the code in the App.js file for setting the subreddit is simply:

import React, { useState } from 'react'
import { Header } from './components/Header/'

function App() {
  const [ subreddit, setSubreddit ] = useState('all')

  return (
    <>
      <Header subreddit={subreddit} setSubreddit={setSubreddit} />
    </>
  )
}

Could someone please explain to me why my code isn’t working as intended and help me fix it?

Thanks in advance!!

Checking instanceof with a class

I have the following code:

function Complex(real, imaginary) {
    let c = Object.create(Complex.methods);
    [c.real, c.imaginary] = [real, imaginary];
    return c;
}

Complex.methods = {
    toString() {return `${this.real}+${this.imaginary}i`},
    add(other) {
        if (!(other instanceof Complex)) throw new Error("Only supports complex-only addition");
        return Complex(this.real+other.real, this.imaginary+other.imaginary);
    }
}
let c1 = Complex(2,0);
let c2 = Complex(3,4);
console.log(c1.add(c2) + "");
// "Uncaught Error: Only supports complex-only addition",

This is occurring because c1 instanceof Complex is returning false. Why does it return false?

Comparing it with using the class keyword:

class CX {
    toString() {return "xxx"}
}
let c1 = new CX();
console.log(c1 + "", c1 instanceof CX);
// xxx true

But still curious why the first one doesn’t recognize the instanceof operator.

A discord.js problem with -play, what the heck am I doing wrong

I’m very new to coding and have heavily been assisted by github copilot but this mess of code from copilot and several tutorials has left me not really understanding why it’s not working. Whenever I run the -play command I keep on getting a “Uncaught SyntaxError SyntaxError: Unexpected identifier at (program) (<eval>/VM46947595:1:8)” which is giberish to me.
also here’s the code

const ytdl = Require('ytdl-core');
const ytSearch = Require('yt-search');
const Message  = Require('discord.js');

const queue = new Map();


export const name = 'play';
export const aliases = ['skip', 'stop', 'pause', 'resume'];
export const cooldown = 0;
export const description = 'dat jazz baby';
export async function execute(message, args, _cmd, _client, _Discord) {

    const voice_channel = Message.member.voice.channel;
    if (!voice_channel)
        return Message.channel.send('you ain't in a voice channel dummy');
    const permissions = voice_channel.permissionsFor(Message.client.user);
    if (!permissions.has('CONNECT') || !permissions.has('SPEAK'))
        return Message.channel.send('I don't have the permissions to join your voice channel');
    if (cooldown[message.author.id])
        return Message.channel.send('You have to wait 5 seconds between commands');
    if (!args[0])
        return Message.channel.send('You need to provide a link');
    if (args[0].startsWith('https://www.youtube.com/watch?v=')) {
        const video = await ytdl.getInfo(args[0]);
        const song = {
            title: video.title,
            url: video.video_url,
            duration: video.length_seconds,
            requester: message.author.username,
            thumbnail: video.thumbnail_url
        };
        if (!queue.has(message.guild.id)) {
            queue.set(message.guild.id, {
                songs: [],
                volume: 5
            });
        }
        queue.get(message.guild.id).songs.push(song);
        if (message.guild.me.voice.channel) {
            play(message.guild.id, message);
        } else {
            message.channel.send('I'm not in a voice channel');
        }
    } else {
        ytSearch(args[0], function (err, r) {
            if (err)
                return message.channel.send('Something went wrong');
            const videos = r.videos;
            if (!videos)
                return message.channel.send('No videos found');
            const first = videos[0];
            const video = ytdl.getInfo(first.link);
            const song = {
                title: video.title,
                url: video.video_url,
                duration: video.length_seconds,
                requester: message.author.username,
                thumbnail: video.thumbnail_url
            };
            if (!queue.has(message.guild.id)) {
                queue.set(message.guild.id, {
                    songs: [],
                    volume: 5
                });
            }
            queue.get(message.guild.id).songs.push(song);
            if (message.guild.me.voice.channel) {
                play(message.guild.id, message);
            } else {
                message.channel.send('I'm not in a voice channel');
            }
        });
    }
}   // end of module.exports

what I’m trying to do is to make a discord music bot and at the very least, make it join the voice channel

Help and or advice is unnecessary but appreciated
Thank you, and have a nice day

How to map JSON key value pairs when object parent name is different each time?

I’m trying to map key value pairs (see investments in the below JSON) but the parent names are all different. It’s proving difficult to search for the answer.

How do I go about targeting these data?

Many thanks in advance!

"quarterly": {
    "2021-12-31": {
            "date": "2021-12-31",
            "filing_date": "2022-01-28",
            "currency_symbol": "USD",
            "investments": "-12929000000.00"
    },
    "2021-09-30": {
            "date": "2021-09-30",
            "filing_date": "2021-10-29",
            "currency_symbol": "USD",
            "investments": "4608000000.00"
    },
    "2021-06-30": {
            "date": "2021-06-30",
            "filing_date": "2021-07-28",
            "currency_symbol": "USD",
            "investments": "5747000000.00"
    },
    "2021-03-31": {
            "date": "2021-03-31",
            "filing_date": "2021-04-29",
            "currency_symbol": "USD",
            "investments": "-7895000000.00"
    }, ...

custom back button for iframe not working

So, this is my body:

<body>
    <div class="s2"><img onClick="document.getElementById('s1').contentWindow.history.back();" class="s2s1" src="Images/back-arrow.svg"></div>
    <iframe id="s1" class="s1" src="https://protohub.online/"></iframe>
  </body>

And nothing happens when I click the image, even when the iframe has history.

Bouncing an object off a wall

I am trying to make a simulation of bouncing object with set borders and angles. I used the JS library P5.js.

My problem is, when the object touches the wall, it does bounce, but it also moves it to wrong position (mainly more to the bottom right).

I created object “Wall”, which is made of two point (A, B) and those points are used to create a linear function, and I use it to determine, whether a point is “behind it”.

f1: y = tg * x + Ax – Ay * tg; tg = (By – Ay) / (Bx – Ax)

f2: y = tn * x + Ox – Ay * tn; tn = Vy / Vx

Then I created an “Object”:

class Obj {
    constructor(x, y) {
        this.pos = createVector(x, y); // Reference position of object
        this.vel = createVector(0, 0); // Velocity of object
        this.acc = createVector(0, 0); // Acceleration
        this.ang = PI / 3;             // Angle
        this.mass = 10;                // *
        this.bouncyness = 0.8;         // *
        this.friction = 0.01;          // *
                                       // Position of points relative to main position (this.pos)
        this.points = [
            { x: -25, y: -25 },
            { x: 0, y: -25 },
            { x: 25, y: -25 },
            { x: 25, y: 0 },
            { x: 25, y: 25 },
            { x: 0, y: 25 },
            { x: -25, y: 25 },
            { x: -25, y: 0 },
        ];
    }


    // ***

    // Updating object properties
    update() {
        for (let point of this.points) {
            const dx = point.x * cos(this.ang) - point.y * sin(this.ang);   // X distance between point and center on screen (counting with angle)
            const dy = point.y * cos(this.ang) + point.x * sin(this.ang);   // Y distance between point and center on screen (counting with angle)
                                      
            for (let wall of walls) {                                       // Looping through walls
                                                                            // Checking if the point is behind the wall
                if (wall.isPointBehind(this.pos.x + dx, this.pos.y + dy)) {
                                                                            // Checking, if the walls are diagonal or vertical
                    if (wall.getDX() == 0) {
                        this.pos.x = wall.A.x - dx;
                    } else if (wall.getDY() == 0) {
                        this.pos.y = wall.A.y - dy;
                    } else {
                        const { x: Ox, y: Oy } = this.pos;      // Position of object
                        const { x: Vx, y: Vy } = this.pos;      // Velocity of object
                        const { x: Ax, y: Ay } = wall.A;        // Position of the first point of the wall
                        const tg = wall.getTG();                // Tan of the angle of the wall: (By - Ay) / (Bx - Ax)
                        const tn = Vy / Vx;                     // Tan of angle of speed

                        // I found the intersection of these 2 linear function by setting f1 = f2 and I got this equasion for x (XX)
                        const XX = (Oy - Ox * tn - Ay + Ax * tg) / (tg - tn);   // Value of x, where the linear functions intersect
                        const YY = XX * tg + Ay - Ax * tg;                      // Y ...

                        // In the end I tried almost everything- calculating it through the point, by difference in positions and many others  but it usually works the same, and this seems to be the closest.
                        const RX = XX - dx;                                     [enter image description here][1]
                        const RY = YY - dy;

                        this.pos = createVector(RX, RY);
                    }
                }
            }
        }

        // ***
    }
}

In the end I tried almost everything- calculating it through the point, by difference in positions and many others but it usually works the same, and this seems to be the closest.

(Sorry if I made some grammatical errors)

Object almost touching the wall

After it touched the wall, it moved more to the right bottomň

Geometrical representation (not very good)

Simpler geometrical representation of ball (circle) object without speed, using just a line perpendicular to the wall

Use string as Javascript variable

I am going through an array with map but I need a received string to be a variable since I am using React Form Hook and when passing string and taking errors it tells me that it does not recognize it.

I tried using eval but it always tells me: ReferenceError: username is not defined

This is my code:

UserFormData.map( ( item, index ) => {
  console.log(item.name); // USERNAME OK
  eval(item.name); // ReferenceError: username is not defined

  let name = item.name

  return (
    <div key={index} className='w-full md:w-1/2 px-4'>
      <label htmlFor= { item.htmlFor}
        className='block uppercase font-bold text-xs mb-2'>
          {item.name}
      </label>
      <input 
        {...register(item.name)} 
        placeholder={ item.placeholder } 
        type= { item.type }
        className={
          `border-0 px-3 py-3 placeholder-blueGray-300
           text-blueGray-600 bg-white rounded text-sm shadow 
           focus:outline-none focus:ring w-full ease-linear 
           transition-all duration-200
           ${ errors.username && "ring-2 ring-red-200 w-full 
              ease-in-out transition-all duration-200"
            }
           `}
        />  
        {errors.username && 
          (<p className='text-xs text-orange-600 mt-2'> { errors.username.message || null } </p>) }

     </div>
     )
})`

I require the string to be a variable since when using React Form Hook in this code it does not recognize the string:

{errors.test && (<p className='text-xs text-orange-600 mt-2'> { errors.test.message || null } </p>) }

This is the data:

const UserFormData =  [
    {
        name: 'username',
        htmlFor:'username',
        placeholder:'Nombre de usuario',
        type:'text',
        register: 'username',
        errors: 'errors.username',
        message: 'errors.test.message'

    }
]

undefined passing to hook

So the code below, I want to pass loc2 into the location hook below and have it like:

const[location, setLocation] = useState({ lng: loc2.lng, lat: loc2.lat});

but when I do the above it says it can’t pass undefined into the hook, but when I console.log it’s not undefined?

const[loc2, setLoc] = useState({ });
    
navigator.geolocation.getCurrentPosition(function(position) {
  let loc3 = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  };
  setLoc(loc3);
                  
  //setLatitude(position.coords.latitude);
  //setLongitude(position.coords.longitude);
}); 

console.log(loc2.lat)

const[location, setLocation] = useState({
  lng: 53.363392004396104,
  lat: -6.209536
});