MUI Grid container height increases as the height of Card increases

I have an MUI Grid container and one of the Grid items have a Card in it. As the text inside the card increases, the height of the Grid too increases. This is usual, but I want the height of all the components to be the same. And if the content inside the card exceeds the height, I want it to overflow with scroll property (only for the card).

Here is my container element

<Grid container p={3} alignItems={"center"} spacing={2} maxHeight={"100%"}>

Here’s my Card element

<Grid item md={8} textAlign={"center"} xs={12}>
                  <Box>
                    {blogTitle === "" ? (
                      <Typography variant="h3" color={"info.main"}>
                        Select a blog to preview
                      </Typography>
                    ) : (
                      <Card sx={{ height: "100%", overflow: "auto" }}>
                        <CardHeader title={blogTitle} />
                        <img src={blogImage} width={500} alt={blogTitle} />
                        <CardContent>{blogDesc}</CardContent>
                      </Card>
                    )}
                  </Box>
                </Grid>

How to achieve nested Slide in MUI

I want to achieve nested slide components with Slide from MUI. Is it possible to have two Slide component inside another, but second one should slide in from the parent Slide component inside of edge of the screen?

I have created a demo in the below sandbox.

https://codesandbox.io/s/misty-dream-f6vcsk?file=/src/App.tsx

As you can see, the second, nested Slide comes from the edge of the screen instead of the parent Slide.

I have checked out this question and added overflow: "hidden". However, it still doesn’t work.

TypeError: Cannot set properties of null (setting ‘textContent’)

can someone please provide a solution to this problem. It doesn’t prevent my web application from running at start but after sometime it just abruptly pops up on the screen.
The error is due to this bit of code.

const animationProjectsCount = () => {
        animate(0, 30, {
            duration: 1,
            onUpdate: (v) => (projectCount.current.textContent = v.toFixed())
        })
}

The entire component code:

import React, { useRef } from 'react';
import { animate, motion } from "framer-motion";
import Timeline from './Timeline';
const Home = () => {
    const projectCount = useRef(null);

    // var element = projectCount.current;

    const animationProjectsCount = () => {
        animate(0, 30, {
            duration: 1,
            onUpdate: (v) => (projectCount.current.textContent = v.toFixed())
        })
    }

    return (
        <div id='about'>
            <div className="abtSections">
                <div className="abtLeft">
                <h1 className='abtHeader'>About</h1>
                    <p>As I strive to achieve my goal of becoming a full-stack developer, I have acquired valuable experience through the completion of various projects at a beginner level, and my accumalated years of programming and project work. Moreover, I possess a notable self aptitude for self-directed learning and am able to apply myself for acquiring new skills at a constrained time frame.</p>
                </div>
                <div className="abtRight">
                    <Timeline />
                </div>
                <div style={{ clear: "both" }}></div>
            </div>
            <div className='projectsDone'>
                <p className='number'>
                    +<motion.span ref={projectCount} whileInView={animationProjectsCount}></motion.span>
                </p>
                <span className='done'>Projects Done</span>
            </div>
        </div>
    )
}

export default Home

Any help would be genuinely appreciated!!

How to pass image and audio from one page to another

I need that it pass image and audio of product to checkout page,I already did that with price of product name and licence I really dont know how , without hardcoding it please can you help me!

heres product page


      <header>
        <!--Nav-->
        <div class="nav container">
          <a href="">Deni Beatz</a>
          <!--Cart Icon-->
          <i class="bx bx-shopping-bag" id="cart-icon"></i>
          <div class="notification" id="cart-notification">0</div>
          <!--Cart-->
          <div class="cart">
            <h2 class="cart-title">Your Cart</h2>
            <!--Content-->
            <div class="cart-content">
              <div class="cart-content">
                
              </div>
            </div>
            <!--Total-->
            <div class="total">
              <div class="total-title">Total</div>
              <div class="total-price" id="total-price total">$0</div>
            </div>
            <!--Buy Button-->
            <form action="checkout.html">
            <button type="button" class="btn-buy" onclick="window.location.href = 'checkout.html';">Continue to purchase</button>
            </form>
            <!--Cart Close-->
            <i class="bx bx-x" id="close-cart"></i>
            <!-- Continue to purchase button moved here -->
          </div>
        </div>
      </header>

          <section id="prodetails" class="section-p1">
            <div class="productcontainer" id="enjoy">
                <div class="single-pro-image">
                  <img src="../data/high.png"  width="100%" id="product-image" class="product-img">
                </div>
            
                <div class="single-pro-details" action="C:sstarter-rubyclientcheckout.html">
                  <h4 class="product-title" id="title">Enjoy</h4>
                  <h2 id="price" class="price">$20</h2>
                  <select id="select" class="licence">
                    <option>Select Licence</option>
                    <option>MP3</option>
                    <option>Tagged Wav</option>
                    <option>Un-Tagged Wav</option>
                    <option>Stems</option>
                    <option>Exlusive</option>
                  </select>
    
                    <script>
                      let select = document.getElementById('select');
                      let price = document.getElementById('price');
    
                      // Prices
                      let prices = {
                        "Select Licence": '$20',
                        "MP3": '$20',
                        "Tagged Wav": '$27',
                        "Un-Tagged Wav": '$30',
                        "Stems": '$120',
                        "Exlusive": '$300'
                      }
    
                      // When the value of select changes, this event listener fires and changes the text content of price to the coresponding value from the prices object
                      select.addEventListener('change', () => {
                        price.textContent = prices[select.value];
                      });
                    </script>
                    <button class="add-cart">Add To Cart <i class='bx bx-cart-add add-cart'></i></button>
                    <h4>Product Details</h4>
                    <span>Lil Tjay x Trap Type Beat - "Enjoy" in key D# Minor and 160 BPM,It has vibe of Lil Tjay , Pop Smoke and more , Prices are great for this type of beat;Tagged Mastered MP3 for $25,$27 for Tagged Unmastered Wav,$30 for Untagged unmastered Wav,$70 for Stems and $120 for Exlusive</span>
                </div>
                <div id="audio">
                    <audio controls style="width:100%;" id="audio-clip">
                        <source src="Audio/Enjoy 160 x D sharp minor.mp3" type="audio/mp3">
                    </audio>
                </div>
              </section> 

    <script>
                var selectedItems = [];
                const addToCartButton = document.querySelector('.add-cart');
                if (addToCartButton) {
                  addToCartButton.addEventListener('click', () => {
                    const productTitle = document.querySelector('#title').textContent;
                    const productPrice = document.querySelector('#price').textContent;
                    const selectedLicense = document.querySelector('#select').value;

                    const cartItem = {
                    title: productTitle,
                    price: productPrice,
                    license: selectedLicense,
                };
              
                    selectedItems.push(cartItem);
              
                    console.log(selectedItems);
              
                    localStorage.setItem('selectedItems', JSON.stringify(selectedItems));
                  });
                }
              </script>
          

and heres checkout page


  <h2 style="text-align:center;">Checkout</h2>
<div id="cart-items">
  <p style="text-align:center;">YOU ADDED THIS PRODUCTS</p>
  <hr />
  <div class="product-container">
      <div class="cart-items"></div>
  </div>
</div>

<div class="total">
  <h3 style="text-align:center;">Tax: <br><span id="tax"></span></h3>
  <h3 style="text-align:center;">Subtotal: <br><span id="subtotal"></span></h3>
  <h3 style="text-align:center;">Total: <br><span id="total"></span></h3>
  <a href="http://localhost:4242"><button style="display:block;">Continue to payment</button></a>
  <a href="http://localhost:4242"><button style="display:block; background-color: rgb(216, 4, 4);">Cancel</button></a> <!--Make next to eachself and red and blue color for button-->
</div>

<script>
const cartItemsDiv = document.querySelector(".cart-items");
const storedCartItem = localStorage.getItem("selectedItems");
const taxRate = 0.1; // 10% tax rate
let subtotal = 0;

if (storedCartItem) {
  const cartItem = JSON.parse(storedCartItem); // Parse the storedCartItem string into an array

  for (let i = 0; i < cartItem.length; i++) {
    const cartItemElement = document.createElement("div");

    cartItemElement.innerHTML = `
    <h3>${cartItem[i].title}</h3>
    <p>Price: ${cartItem[i].price}</p>
    <p>License: ${cartItem[i].license}</p>
    `;
    cartItemsDiv.appendChild(cartItemElement);

    const price = Number(cartItem[i].price.replace("$", "")); // Parse price as a number and remove dollar sign
    subtotal += price;
  }

  const subtotalElement = document.querySelector("#subtotal");
  subtotalElement.textContent = `$${subtotal.toFixed(2)}`;

  const taxElement = document.querySelector("#tax");
  const tax = subtotal * taxRate;
  taxElement.textContent = `$${tax.toFixed(2)}`;

  const totalElement = document.querySelector("#total");
  const total = subtotal + tax;
  totalElement.textContent = `$${total.toFixed(2)}`;
}
</script>

It display name licence and price of added products but now i need that it display image and audio of added product without hardcoding it !

To add a button that autofills a random password on the password field which I created using py-script

I created a form in html which returns to a function in views.py in django framework. I wanted to add a button which autofills the password field with a random password. I used pyscript for creating a random password. But the button seems to be returning to the views.py instead of autofilling.

<body bgcolor="white">
    <py-script>
    import random
    password = ''
    def mypass():
       length = random.randint(8,16)
       list1=[]
       for i in range(0,length):
           list1.append(chr(random.randint(32,126)))
       password = ''.join(list1)
    pyscript.write('python', password)
    </py-script>
    <script>
        function myfun(){
            var a = document.getElementById("password1").value;
            var b = document.getElementById("password2").value;

            if(a!=b){
                document.getElementById("messages").innerHTML="Passwords do not match";
                return false;
            }
        }
    </script>
    <script>
        function myfunction(){
            var password = PyScript.interpreter.globals.get('password');
            document.getElementById("password1").value = password;
       } 
    </script>
    <form onsubmit="return myfun();" action="register" method="post" >
        {% csrf_token %} 
        
        <p>
            <label for="user_name">User Name</label>
            <input type="text" name="user_name" id="user_name" placeholder="Antman56." autocomplete="on" >
        </p>
        <p>
            <label for="f_name">First Name</label>
            <input type="text" name="f_name" id="f_name" placeholder="Dave" autocomplete="on" >
        </p>
        <p>
            <label for="l_name">Last Name</label>
            <input type="text" name="l_name" id="l_name" placeholder="Lee" autocomplete="on" value="keyan" >
        </p>
        <p>
            <label for="email">Email ID</label>
            <input type="email" name="email" id="email" placeholder="[email protected]" autocomplete="on" >
        </p>
        <p>
            <label for="password1">Password</label>
            <input type="password" name="password1" id="password1" placeholder="123$aBc" >
        </p>
        <p>
            <label for="password2">Confirm Password</label>
            <input type="password" name="password2" id="password2" placeholder="123$aBc" ><span id="messages" style="color:red"></span>
        </p>
        <div id="python"></div>
        <button onclick="mypass()">create random password</button>
        <button onclick="myfunction()">fill the random password</button>
        <input type="submit" value="Submit" >
      
    </form>

when I click the ‘create random password’, I expect the mypass function in pyscript to execute and when I click the ‘fill the random password’ button, I want to execute the myfunction function and autofill my password field with the random password previously generated.

How can I work out form submission calculations using JavaScript? [closed]

I have built an order form with lots of different products on it for a butchers. Each product has the following:

<div class="col text center">Shin of Beef <br>€9.50 per kilo</label>
    <br>
    <select id="old english" name="oldenglish">
        <option value="0">---------</option>
        <option value="1">1 Kilo</option>
        <option value="2">2 Kilos</option>
        <option value="3">3 Kilos</option>
        <option value="4">4 Kilos</option>
        <option value="5">5 Kilo</option>
        <option value="6">6 Kilos</option>
        <option value="7">7 Kilos</option>
        <option value="8">8 Kilos</option>
        <option value="9">9 Kilos</option>
        <option value="10">10 Kilos</option>
        <option value="11">11 Kilos</option>
        <option value="12">12 Kilos/option>
        <option value="13">13 Kilos</option>
        <option value="14">14 Kilos</option>
        <option value="15">15 Kilos</option>
        <option value="16">16 kilos</option>
        <option value="17">17 Kilos</option>
        <option value="18">18 Kilos</option>
        <option value="19">19 Kilos</option>
        <option value="20">20 Kilos</option>
    </select>

    </select>
    <br><label for="weight">Enter Weight</label>
    <input type="number">

I need to know how I can use JavaScript to select an option and show a price so say 2 packs is €9.50 x2 and it will calculate the prices once 2 packs are selected.

How do i calculate the time remaining between the current time and a set time in javascript

I want to create a prayer app where it tells you how much time is left between current time and the time of the prayer

I tried to find the difference directly by doing this

let left = new Date(currprayer.getTime() - time.getTime() );
            document.getElementById('nextmin').innerHTML = left.getMinutes()
            document.getElementById('nexthrs').innerHTML = left.getHours()
            document.getElementById('nextsec').innerHTML = left.getSeconds()

HTML:

 <div class="details">
                <div class="next-prayer">
                    <span id="nexthrs">00</span>
                    <span>:</span>
                    <span id="nextmin">00</span>
                    <span>:</span>
                    <span id="nextsec">00</span>
                </div>
            </div>

but it keeps getting stuck on 00:00:00

How to generate tuple type annotation for each key in an object in Typescript

I have an object in which for each key of the object, I want to create a tuple such that it is of the format
[k, typeof O[k]]
Where O is the Object, k is a key in the object.

So for example, consider the object below
{ content: "", isReady: false }
I want to generate a tuple type annotation that is as follows
['content', string]|['isReady', boolean]

How do I do that? By the way, I am using jsDoc to document the types, but I don’t mind getting the typescript typing version. Thank you in advance

I tried using the following type annotation
[keyof typeof Object, typeof Object[keyof typeof Object]]
But it’s not giving me the desired result

React player video length estimation fails on Chrome but succeeds on Firefox

I have an application which’s using React Player to play mp4 files which are located in Firebase.

For some odd reason, the video’s length in Firefox is calculated straight as page loads:
enter image description here

While in chrome, it doesn’t:
enter image description here

This issue causes my in Chrome to to users not being able to change to the time in the video they wish to play, until the video is almost fully loaded, then it shows the video’s total duration and then the user is also able change via the seek bar. It also pops the following error:

When I try to print playerRef.current.getDuration(), I get value of Infinity.

I have tried adding custom headers to the firebase’s put function:

  const headers = {
    "Content-Length": estimatedVideoLength.toString(),
    "Content-Type": file.type,
  };

without a success.

I have no idea what else could I do.
Any ideas? :_)

How to dynamically change the cursor color(caret-color) of Codemirror(v5) text area in react?

I am building a web application for a real time code editor using web sockets in React/Nodejs. In a particular room when more than one user are simultaneously typing out the code in the editor built with Codemirror version 5.65.12, I want to indicate which user is currently typing based on the cursor/caret color. I am randomly generating a color for all the different user in the room and want to emit this color to the room wherein I can set the color of the caret to match the active user. I am struggling to change the color of the caret.

Here’s how I’ve initialized the editor:

editor.current = Codemirror.fromTextArea(
    document.getElementById("realtimeEditor"),
    {
      autoCloseTags: true,
      autoCloseBrackets: true,
      lineNumbers: true,
      mode: "clike",
      theme: "dracula",
    }
);

where editor = useRef(null)

Similarly, I’ve used another useref cursorRef = useRef(null)

And I’m trying to access the class .CodeMirror-cursor with the following code:

cursorRef.current = editor.current.display.cursorDiv.childNodes[0];
if (cursorRef.current) {
   cursorRef.current.style.setProperty(
     "border-color",
     "yellow",
     "important"
   );
   console.log(cursorRef.current.style.borderColor);
}

The console.log() outputs the value as yellow, but the color doesn’t actually change in the editor. Where am I going wrong?

What is the ‘prototype’ property of a React component?

MDN says that every JavaScript object has a prototype property that is not actually called prototype:

Every object in JavaScript has a built-in property, which is called
its prototype. … The property of an object that points to its
prototype is not called prototype. Its name is not standard, but in
practice all browsers use __proto__. The standard way to access an
object’s prototype is the Object.getPrototypeOf() method.

Why then do React components have a property called exactly prototype?

I can see this property from the Javascript console when creating a React app with create-react-app and logging App.prototype to the console:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

console.log(App.prototype); 

The log returns an object.

How to create json array using FormData in Reactjs

How can I convert this json Object to formData? I’m getting this json in onFinish function

{
    design_name_code: "Hiroko Lloyd",
    design_name: "Darius Huff",
    design_photo: [],
    fabrics: [
        {
            fabricName: "Georgette",
            colors: [
                {
                    color: "red"
                },
                {
                    color: "pink"
                }
            ]
        },
        {
            fabricName: "Silk",
            colors: [
                {
                    color: "Yellow"
                }
            ]
        }
    ],
    designers: [
        "643a33012e54c21e2409fa86"
    ]
}

onFinish function

const onFinish = (values) => {
     const formData = new FormData();

    formData.append("design_name", values.design_name);

    formData.append("design_name_code", values.design_name_code);

    if (values.design_photo) {
      formData.append("design_photo", designImage);
    }

    values.fabrics?.forEach((data, index) => {

      formData.append(`fabric[${index}].fabric_name`, data.fabricName);

      data.colors.forEach((clr, clrIndex) => {
        formData.append(`fabric[${index}].colors[${clrIndex}].color`, data.colors[clrIndex].color);
      })

    });

    values.designers?.forEach((data, index) => {
      formData.append(`designer[${index}]`, data)
    })

    console.log(values);
  };

here when the form submit, I get the json object (as you can above), after that I create the formData of that json Object (you can see on onFinish function), here I’m facing a challenge in fabrics object

Creating Discord bot causes error Javascript

This is my first attempt to make a bot that creates a new temporary channel each time a message is posted to a specific channel. I am a bit lost now, any help appreciated.
I get this error in VSCode when I post to my channel:

DiscordAPIError[50035]: Invalid Form Body
name[BASE_TYPE_REQUIRED]: This field is required at handleErrors (c:UsersUserOneDriveJavascriptnode_modules@discordjsrestdistindex.js:640:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (c:UsersUserOneDriveJavascriptnode_modules@discordjsrestdistindex.js:1021:23)
at async SequentialHandler.queueRequest (c:UsersUserOneDriveJavascriptnode_modules@discordjsrestdistindex.js:862:14)
at async REST.request (c:UsersUserOneDriveJavascriptnode_modules@discordjsrestdistindex.js:1387:22)
at async GuildChannelManager.create (c:UsersUserOneDriveJavascriptnode_modulesdiscord.jssrcmanagersGuildChannelManager.js:170:18)
at async Client. (c:UsersUserOneDriveJavascriptbotmanager.js:19:25) {
requestBody: {
files: undefined,
json: {
name: undefined,
topic: undefined,
type: undefined,
nsfw: undefined,
bitrate: undefined,
user_limit: undefined,
parent_id: undefined,
position: undefined,
permission_overwrites: undefined,
rate_limit_per_user: undefined,
rtc_region: undefined,
video_quality_mode: undefined,
available_tags: undefined,
default_reaction_emoji: undefined,
default_auto_archive_duration: undefined,
default_sort_order: undefined,
default_forum_layout: undefined
}
},
rawError: {
code: 50035,
errors: { name: [Object] },
message: ‘Invalid Form Body’
},
code: 50035,
status: 400,
method: ‘POST’,
url: ‘https://discord.com/api/v10/guilds/[channelID]/channels’
}

My Code ——————————

`
const { token } = require("./config.json");
const Discord = require("discord.js");
const { Client, Intents, MessageEmbed, Message } = require("discord.js");

const client = new Client({
  intents: [
    Discord.GatewayIntentBits.Guilds,
    Discord.GatewayIntentBits.GuildMembers,
    Discord.GatewayIntentBits.GuildMessages,
  ],
});
client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}`);
});

client.on("messageCreate", async (message) => {
  try {
    if (message.channel.id !== "channelID") {
      return;
    }

    // Create the temporary channel
    const tempChannel = await message.guild.channels.create(
      `${message.author.username}-temp-channel`,
      {
        type: "GUILD_TEXT",
        parent: message.channel.parent,
        permissionOverwrites: [
          {
            id: message.guild.roles.everyone,
            allow: ["VIEW_CHANNEL"],
          },
        ],
      }
    );

    // Copy the message to the temporary channel
    await tempChannel.send({
      content: `Message from ${message.author.tag} in ${message.channel.name}: ${message.content}`,
      files: message.attachments.map((a) => a.url), // copy any attachments
    });

    // Delete the temporary channel after 12 hours
    setTimeout(() => {
      tempChannel.delete();
    }, 43200000);
  } catch (error) {
    console.error(error);
  }
});
client.on("error", console.error);
client.login(token);
`

I have tried a bit, I think there is a problem with name, but not sure how to fix.

Error at uploading image Realtime firebase react native expo?

I am getting Possible Unhandled Promise Rejection (id: 0): TypeError: undefined is not an object (evaluating 'ref._location') and I don’t know why?
I even change ref as

import { ref as refstore, uploadBytesResumable, getDownloadURL } from "firebase/storage";

So that don’t collide with each other. and changes images to blob. I am stuck here not sure what to do next.

const uploadImage = async () => {
  const blobimage = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function () {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", imageUri, true);
    xhr.send(null);
  })

  const metadata = {
    contentType: 'image/jpeg'
  };
  // I think something is wrong in the below line **storageRef** <------------
  const storageRef = refstore(storage,`images/${Date.now()}`);
  const uploadTask = uploadBytesResumable(storageRef, blobimage, metadata);

  uploadTask.on('state_changed',
    (snapshot) => {
      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case 'paused':
          console.log('Upload is paused');
          break;
        case 'running':
          console.log('Upload is running');
          break;
      }
    },
   
    
  );
};