Trying to drag and drop onto an SVG canvas with accurate coordinates

I am trying to implement drag and drop an image element onto an SVG canvas but the elements are not in the same div. I have tried to use clientX and clientY properties but they are out by about 20 pixels when I come to drop the element. I think the problem is that the SVG coordinates work from the top of the root SVG element but drag and drop coordinates are from the visible view port. When I try to release the rock image on the canvas it just seems to go to any random place on it and sometimes off the canvas completely.

Screenshot of my attempt

I have uploaded all my code to https://github.com/kiwiheretic/gravity

Any idea what javascript mouse event attributes and element attributes to work out my SVG coordinates for drag and drop?

How to download csv file with react and ANTD

Im using Ant Design Pro for UI development with react. I want to Download Sample CSV file When i click a download button. I tried many ways to do that but some errors are coming with the code. The CSV file is reading the data when it import.

import SampleCSV from '../../../../assets/documents/Sample.csv';

<Button type="link" href={SampleCSV} download={'Sample CSV'}>Download Sample CSV File</Button>

enter image description here

react-native: The term ‘react-native’ is not recognized as a name of a cmdlet, function, script file, or executable program

I’ve been trying to use custom fonts in my react-native app but I keep getting the error “react-native: The term ‘react-native’ is not recognized as a name of a cmdlet, function, script file, or executable program” whenever I type react-native link to link my react-native.config.js file to my project. Any help please?

–I’m operating on Linux Mint

How Can I Change Constant Array in Javascript?

I have an array data but it declared with const. I am rather confused to change the data in array. Here is my array:

const person = {
   name: "Person A", ---> the data I want to change
   age: 100,
   favDrinks: [
     "coffee",
     "temulawak", --->> the data I want to change
     "tea"
       ],
 greeting: function() {
     console.log("Hello World"); --->> the data I want to change
   }
 }

How can I change the data of person.name, person.favDrinks[1], and greeting function of “Hello World”. Is there a possible way to change constant data? I want to change to text strings. Here is my code :

function personName(nama ){
  let person.name = nama;
    person.push("name:" nama );

}

console.log(personName("Molly"));

But they are all wrong. Please help me. Thank you. 🙂

How do I make a reusable component for the Cards and how can I use the new makeStyles of material-ui?

In the demo.js, I wanted to use the Card along with its CardHeader and put wordings inside the CardContent. Also, I will be using the CardComponent in other files as well. How can I make the CardComponent reusable?

Sample codes: https://codesandbox.io/s/basiccard-material-demo-forked-kkshx?file=/demo.js

Below are the codes for the demo.js:

import * as React from "react";

import CardComponent from "./CardComponent";

export default function BasicCard() {
  return (
    <>
      <h1>Hello</h1>
      <CardComponent />
    </>
  );
}

Below are the codes for the CardComponent:

import React from "react";

import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import { CardHeader } from "@mui/material";

const CardComponent = () => {
  const CardStyle = {
    maxWidth: 500,
    margin: "0 auto",
    marginBottom: "1rem",
    marginTop: "1rem"
  };
  return (
    <Card sx={{ minWidth: 275 }} elevation={5} style={CardStyle}>
      <CardHeader title="Card Header Title here" />
      <CardContent>//content here</CardContent>
    </Card>
  );
};

export default CardComponent;

I have another question as well under this component. Coming from material-ui4, mui5 was kind of confusing as I can no longer use the makeStyles. I tried adding this in the codesandbx example, however, it will say that dependency not found:

import { makeStyles } from '@mui/styles';

Hence, I settled with const CardStyle. Any help on how can I implement the newer version of the makeStyles? Also, do I need to install other dependecies from material-ui to make it work? Below is the package.json file.

enter image description here

Array print element index 0 as index 1

How can I print the output as

17 in 1 days

21 in 2 days

23 in 3 days

and not

17 in 0 days

21 in 1 days

23 in 2 days

const arr = [17, 21, 23];

const printForecase = function() {
    for (let i = 0; i < arr.length; i++) {
        console.log(`${arr[i]} in ${i} days`);
    } } 
printForecase();

How can I validate a input type=’file’ in react-hook-form?

I am using react hook form for my project. How can i validate input type=’file’? It should only accept pdf. It was successfully inserted into database now when i want that only pdf should should be allowed. I am using react hook form v7.If someone knows plz suggest me. Thanks in advance!

Here’s my code

import React from 'react'

import { useForm } from 'react-hook-form';
import { ToastContainer, toast } from 'react-toastify';


export const Workshop = () => {
  const { register, handleSubmit, formState: { errors }, reset } = useForm();

  const onSubmit = async (data, e) => {

    const formData = new FormData();
    formData.append('workshop',data.workshop)
    formData.append('participants',data.participants)
    formData.append('startdate',data.startdate)
    formData.append('selectedfile',data.selectedfile[0])
    formData.append('establishmentdate',data.establishmentdate)
    console.log(data)
    reset()
    const requestOptions = {
      method: 'POST',
      // headers: { 'Content-Type': 'application/json' },
      body: formData
    };

    const response = await fetch("http://localhost:3001/workshop", requestOptions);
    try {
      if (response.status == 200) {
        toast.success("Successfully added");
      }
    }
    catch {
      toast.error("Invalid");
    }
    const jsonData = await response.json();
    console.log(jsonData)

    // toast.error("Invalid"); 


  };

  return (
    <div className="container ">
      <ToastContainer />
      <form onSubmit={handleSubmit(onSubmit)}>
        <div class="mb-3 mt-5" >
          <h2>Details of Workshops/Seminars
          </h2>
          <label for="exampleFormControlInput1" class="form-label">Name of the workshop/ seminar
          </label>
          <input type="text" class="form-control w-25" name="workshop" id="exampleFormControlInput1" {...register("workshop", { required: true, pattern:{value:/^[a-zA-Z]+$/ ,message:'Only characters allowed'}})} />
          {errors.workshop && errors.workshop.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.workshop && errors.workshop.type === "pattern" && (
        <div style={{color:'red'}}> Only characters allowed</div>
      )}
        </div>
        <div class="mb-3 w-25 ">
          <label for="exampleFormControlTextarea1" class="form-label">Number of Participants
          </label>
          <input type="text" class="form-control" id="exampleFormControlTextarea1" name="participants" {...register("participants", { required: true, pattern:{value:/^[0-9b]+$/ ,message:'Only characters allowed'}})} />
          {errors.participants && errors.participants.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.participants && errors.participants.type === "pattern" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>
        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Date From – To
          </label>
          <input type="date" class="form-control" id="exampleFormControlTextarea1" name="startdate" {...register("startdate",{required:true})} />
          {errors.startdate && errors.startdate.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.startdate && errors.startdate.type === "valueAsDate" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>

        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Link to the Activity report on the website(Upload PDF)
          </label>
          <input type="file" class="form-control" id="exampleFormControlTextarea1" name="selectedfile" {...register('selectedfile', {
            required:true,
            
          })} />
          
        </div>
        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Date of establishment of IPR cell
          </label>
          <input type="date" class="form-control" id="exampleFormControlTextarea1" name="establishmentdate" {...register("establishmentdate",{required:true})} />
          {errors.establishmentdate && errors.establishmentdate.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.establishmentdate && errors.establishmentdate.type === "valueAsDate" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>

        <button type="submit" class="btn btn-primary me-md-2">Submit</button>
        <button type="button" class="btn btn-primary me-md-2" >Download Excel</button>
        <button class="btn btn-primary me-md-2" >Download PDF</button>
        <button class="btn btn-primary me-md-2" >Download Word</button>

      </form>
    </div>
  )
}

How should I fix this?

Anime.js not working with CSS color: transparent for background maks

I’m playing around with anime.js at the moment, trying to get some text effects. The idea is ultimately to have an adjective shifting within an otherwise fixed header message, which is why I’ve layered the text with grid.

At the same time, I’ve added a background image/mask with ‘-webkit-background-clip: text’ and ‘color: transparent’, in order to add some styling to the text that will animate in/out. The background mask works by itself, and the animation works by itself. However, together they break: nothing shows up. Any color value other than transparent works; however, this of course means that I can’t combine the masking technique with the animation. Does anyone know why this is breaking/how to fix? Thank you!


    <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" href="./test.css">
        <script src='https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js'></script>
    </head>
    <body>  
        <div class='mask'>
            <h1 class='word1'>
                <span>h</span><span>e</span><span>l</span><span>l</span><span>o</span>
                <span>w</span><span>o</span><span>r</span><span>l</span><span>d</span><span>!</span>
            </h1>
            <h1 class='word2'>
                <span>L</span><span>o</span><span>r</span><span>e</span><span>m</span>
                <span>I</span><span>p</span><span>s</span><span>u</span><span>m</span>
            </h1>
        </div>
    </body>
    
    <script>
    let animation = anime.timeline({
        loop: true
    });
    animation.add({
    targets: '.word1 span',
      rotateX: 110,
      borderRadius: 50,
      duration: 2000,
      easing: 'linear',
      loop: true,
      delay: anime.stagger(150),
      opacity: 0
    })
    animation.add({
    targets: '.word2 span',
        opacity: 1,
        rotateX: [-110, 0],
      borderRadius: 50,
      duration: 2000,
      easing: 'linear',
      loop: true,
      delay: anime.stagger(100),
    })
    </script>
    </html>


    div {
        display: grid;
        grid-template-columns: 1;
        grid-template-rows: 1;
    }
    
    span {
        display: inline-block;
        margin: 0;
        letter-spacing: normal;
    }
    
    .word1,
    .word2 {
        grid-area: 1/1;
    }
    
    .word2 span{
        opacity: 0;
        transform: rotateX(110deg);
    }
    
    .mask {
        -webkit-background-clip: text;
        background-image: url('./copy_texture_4_small.jpg');
        color: transparent;
    }

How to select multiple elements with JQuery?

My objective is making a function to toggle password visibility. The problem is that in the same Doc I have 3 different inputs that I also need the toggle visibility function, tho these inputs are not related to the password.

I tried with the name attribute, but it felt like over complicating, since I had names for each icon and input.I have no idea what to use to make the function, and I know there must be an easier way.

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
@Html.PasswordFor(m => m.Password, new { @class = "form-control", maxlength = 50 })

What does “set serverURL” mean? I would have expected to see “setServerURL” [duplicate]

I’m puzzled by this syntax that I found in the Parse class in the Javascript SDK, and it seems impossible to google it due to the commonness of the word “set”.

   * @member {string} Parse.serverURL
   * @static
   */
  set serverURL(value) {
    _CoreManager.default.set('SERVER_URL', value);
  },

  get serverURL() {
    return _CoreManager.default.get('SERVER_URL');
  },

    

I would expect to see setServerUrl. But the space is weirding me out. Some kind of property syntax?

It looks like a syntax error, but it seems to work.

I’m guessing somebody will yell at me for this question. Sorry in advance.

typescript use preset value for property value in array object error?

I have this simple typescript code for react

type fruitCode = 'apple' | 'banana'
  interface fruitList {
    name: fruitCode
  }

  const [arr, setArr] = useState<fruitList[] | []>([])


  useEffect(() => {
    const arrList = [{
      name: 'apple'
    }, {
      name: 'banana'
    }];

    //error?
    setArr(arrList)

  }, [])

demo
https://codesandbox.io/s/react-typescript-forked-gi6fw?file=/src/App.tsx:103-391

how can I restrict my property value is either ‘apple’ and ‘banana’?

how to pass object’s method as parameter in javascript

Hello I’m trying to bulid my own function that allows me to create html tags as below , and Im using object as argument to the function

function create_element(arg){

const element = document.createElement(arg.tag);//  Create element

if(arg.text){element.innerText = arg.text;} // Add text to element
if(arg.id){element.setAttribute("id",arg.id)} // Add ID

if(arg.hello){
    arg.hello = function(x){
        console.log(`Hello ${x}`)
    }
}

}

create_element({
    tag:"div",
    id:"id1",
    text:"this is a text",
    hello:hello("name")

})

my question is how to execute hello function? tag , id and text are working well, thank you kindly.

What JS syntax is used for this function parameter?

What kind of parameter is this? { children }: { children: JSX.Element }

This is the function declaration

function RequireAuth({ children }: { children: JSX.Element }) {
  let auth = useAuth();
  let location = useLocation();

  if (!auth.user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

I know that the function takes JSX component, but I still don’t know which syntax the parameter uses.