e.preventDefault and onSubmit does not prevent page from reloading on react [duplicate]

i have a form that has only a select option, i am using mantine component there is no button on the form, so when i select an option and hit enter it submits. The problem is that the entire page refreshes. I have added e.preventDefault and even e.stopPropagation and the page still refreshes when i press enter. To get the form to even submit i had to use ref and onKeyUp to call the submit function. How do i prevent the page from refreshing and still submit.

Submit function

  const selectForm = useRef(null);
  function handleSubmit(e) {
    
    e.preventDefault();
    e.stopPropagation();
    if (e.keyCode === 13) {
      e.preventDefault();
      e.stopPropagation();
    selectForm.current.submit();
    }
    
    setJoblist("");
    console.log(joblist);
    setLoading(true);
    const uu = {
      jobs: joblist,
    };
    console.log(uu);
    console.log(api.jobs);
  }

My form

 <form ref={selectForm} onKeyUp={handleSubmit} tabIndex={0}>
        <Select
          label="Your favorite framework/library"
          placeholder="Pick one"
          searchable
          clearable
          nothingFound="No options"
          value={joblist}
          onChange={setJoblist}
          data={[
            { value: "react", label: "React" },
            { value: "ng", label: "Angular" },
            { value: "svelte", label: "Svelte" },
            { value: "vue", label: "Vue" },
          ]}
          style={{
            width: "608px",
            marginLeft: "294px",
            marginTop: "-100px",
          }}
        />
  </form>

Creating an input for a dice roller in React (javascript)

I am making a dice roller in javascript with React. Basically, I have an array with dice values and a loop that runs through them to render dice for the user to roll. I’m now trying to create an input so the user can make a new die with any number of sides, but I’m having trouble connecting that input to the rest of my code. Please let me know if you have any ideas about how I could do this with javascript! Thanks!

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function RenderButtons(props){
  return(
      <button className="center" data-index={props.index} id="roller" onClick={props.onClick}>
        {props.value.current} /{props.value.max}
        </button>
  )
}

class Roller extends React.Component {
  constructor(props) {
    super(props);
    this.roll = this.roll.bind(this)
    this.state = {
      diceValues: [
        {max:100, current:100},
      ],
    }
  }

  roll(evt) {
    let min = 1;
    let max = this.state.diceValues[evt.target.dataset.index].max
    let result = Math.floor(Math.random() * (max - min) + min);

    const diceValues = this.state.diceValues.slice();
    diceValues[evt.target.dataset.index].current = result + 1;
    this.setState({diceValues: diceValues});
  }

  makeDie(i) {
    return(
      <RenderButtons
      key = {i}
      onClick = {this.roll}
      value = {this.state.diceValues[i]}
      index = {i}
      />
    )
  }
  render() {
    let buttonsToMake = [];
    for (let i = 0; i < 1; i++){
      console.log("rendering buttons")
      buttonsToMake.push(this.makeDie(i))
      return (
        <div>
          <input
          type="number"
          placeholder="Custom Dice"
          ></input>
          <button
          // id="input"
          // value={this.state.value}
          // onChange={console.log(this.state.value)}
          // {this.handleChange}
          >
          Generate Die
          </button>
          {buttonsToMake}
        </div>
        )
    }
  }
}

ReactDOM.render(
  <Roller />,
  document.getElementById('root')
);

What does [, mean in javascript method signature documentation?

I’m reading a blog article about how to use the forEach() method in javascript, and what it gives to explain which parameters this method takes is this:

array.forEach(callback(currentVal [, index [, array]])[, thisVal])

what’s the correct way to read these “structures”:

currentVal [, index [, array]] and [, thisVal]

Why does it look like currentVal, index, and array are in a nested structure?

Why not just use , instead of [,. I’m sure there’s a good reason, but I just don’t know what it is. I see this format a bunch in documentation all the time, but have never picked up why it’s written like this.

React resizing img not working (Material UI useStyles)

I am trying to resize an image in React, but for some reason changing the height and width of the tag via useStyles does not make the image smaller, but simply shifts it around in the page.

Code:

import { makeStyles } from "@material-ui/core/styles";
import { SvgIcon, Typography } from "@mui/material";
import { Icon } from "@mui/material";

const useStyles = makeStyles((theme) => ({
  pageContainer: {
    display: "block",
    marginTop: 120,
    justifyContent: "center",
    alignItems: "center",
  },
  logo: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    width: "50%",
    height: "50%",
  },
  info: {
    display: "block",
    justifyContent: "center",
    alignItems: "center",
  },
  iconContainer: {
    display: "flex",
    height: "20vh",
    width: "auto",
  },
}));

const teamNames = [
  "Name1",
  "Name2",
  "Name3",
  "Name4",
];

export default function () {
  const classes = useStyles();
  return (
    <div className={classes.pageContainer}>
      <div className={classes.logo}>
        <img src={process.env.PUBLIC_URL + "/myLogo.png"}></img>
      </div>
      <div className={classes.info}>
        <Typography variant="h3" display="block" align="center">
          About the Team
        </Typography>
        {teamNames.map((personName) => (
          <Typography variant="h5" display="block" align="center">
            {personName}
          </Typography>
        ))}
      </div>
    </div>
  );
}

I’m not quite sure what is the issue, all I really want to do is to make the image smaller proportionally and put it at the center of the page.

Error in displaying where there’s an a array inside of the object

this is what the data shows inside the console:

enter image description here

I tried displaying it with these but it failed

 {Object.entries(value).map(([key, value]) => {
        return (
          <p key={key}>
            <li>
              {key}
              {value}
              {console.log(value.id)} //this will show as undefined
            </li>
          </p>
        );
      })}

{value} will show this error :

Objects are not valid as a React child (found: object with keys {color, quantity}). If you meant to render a collection of children, use an array instead.

{value.id} or the {value.name} will show as undefined

With the map, it will say that value.map is not a function

 {value.map((value, key) => (
    <>
      <div>{value.id}</div>
      <div>{value.name}</div>
    </>
  ))}

codesandbox: https://codesandbox.io/s/display-the-manipulated-data-dy204r

React.js– storing input data into varible

I am trying to put input data into a variable from within a component, and I want to use that variable to pass it through a function within my main.js file. The function puts random letter into an interval, I already have it working with a button, but I would like users to be able to input their own letters. I already have the input data being rendered on the page using state, however, I do not know how to convert that data into a variable and use it on another page. Thanks for the help everyone!

This is my input component:

import "./Input.css";
import React, { useState } from "react";

function Input(props) {
  const [data, setData] = useState(null);
  function getData(e) {
    setData(e.target.value);
  }
  function handleSubmit(e) {
    e.preventDefault();
  }

  return (
    <div>
      <h1>Your custom letter set: {data} </h1>
      <form onSubmit={handleSubmit}>
        <input onChange={getData} className="inputField" type="text" placeholder="Enter letters here, separate by commas" />
        <button onClick={props.click4} value="Start">
          Start
        </button>
      </form>
    </div>
  );
}

export default Input;

This is my main JS file:

import React, { useState } from "react";
import "./App.css";
import Chalkboard from "./chalkboard/chalkboard";
import StartStop from "./startStopButtons/startStopButtons";
import LevelBoxes from "./levelBoxes/levelBoxes";
import Input from "./Inputs/Input";

function App() {
  var _timer;
  var vowels = "aeiouy".split("");

  // Function that starts the letter interval

  const startFunction = () => {
    var allLetters = "abcdefghijklmnopqrstuvwxyz".split("");
    getRandom(allLetters);
  };

  // Stops startFunction

  const stopButton = () => {
    clearTimeout(_timer);
    clearTimeout(getRandom);
  };

  // function that sets certain letters into interval 

  function getRandom(letters) {
    var randomSet = letters[Math.floor(Math.random() * letters.length)];
    console.log("set random", randomSet);
    document.getElementById("demo3").innerHTML = randomSet;
    _timer = setTimeout(() => getRandom(letters), 1000);
  }

 //Here I would like to use the Var to insert into function like so

const inputData = () => {
    var inputDataInput;
    getRandom(inputDataInput);
  };

  }

  return (
    <div className="App">
      <h1>Letter Interval Application</h1>

      <Chalkboard click={myFunction} />

      <Input clickStart={startFunction} click4={inputData} />
 
      <LevelBoxes clickStart={startFunction} />

      <StartStop clickStop={stopButton} />

    </div>
  );
}

export default App;

Is it possible to use Graphql query with React Class component?

I need to transform this component to a class component, how can I replace useQuery hook?

  import {useQuery, gql} from "@apollo/client";

const getBooks = gql`
  {
    books {
      name
    }
  }
`;

function BookList() {
  const {loading, error, data} = useQuery(getBooks);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error </p>;
  console.log(data);
  return (
    <div>
      <ul id="book-list">
        {data.books.map(book => (
          <li key={book.id}>{book.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default BookList;

Web pages from coding area [closed]

Consider a set of web pages, numbered from 1 to N. Each web page has links to one or more web pages. Clicking on a link in a page, takes one to the other web page. You are provided numbers of two web pages viz, starting web page and end web page. Your task is to find the minimum number of clicks required to reach the end page from the start page. If end page cannot be reached from start page, print -1 as the output. For better understanding refer Examples section.

Vue 3/Quasar: Handling opening and closing of modals

I have two modals:

One is a Sign Up modal which takes in information of an existing user. Another modal which allows an existing user to login.

The only way to get to the Login modal is through the Signup modal.

But what I would like to do is, if the use wants to open the Login, I would like to close the Sign up modal first.

Right now that seems impossible with my setup. With the code below (nextTick), it does not work and closes both modals… despite there being a unique v-model for each modal.

Sign up Modal

<template>
    <AVModal
        :title="$t('signup.create_an_account')"
        :button-text="$t('signup.button_text')"
        classes="hide-icon q-mt-sm"
        modal-style="width: 350px"
        v-model="modal"
    >
        <q-form
            @submit="signUp(user)"
            class="row column fitq-gutter-md q-gutter-md"
        >
            <q-input
                outlined
                v-model="signup_user.username"
                :label="$t('signup.name')"
            >
                <template v-slot:append>
                    <q-icon name="person" color="grey" />
                </template>
            </q-input>
            <q-input
                outlined
                v-model="signup_user.email"
                type="email"
                :label="$t('signup.email')"
            >
                <template v-slot:append>
                    <q-icon name="email" color="grey" />
                </template>
            </q-input>
            <q-input
                outlined
                v-model="signup_user.password"
                type="password"
                :label="$t('signup.password')"
            >
                <template v-slot:append>
                    <q-icon name="lock" color="grey" />
                </template>
            </q-input>
            <q-checkbox
                v-model="signup_user.privacy_policy"
                color="secondary"
                :label="$t('signup.privacy_policy')"
            />
            <q-checkbox
                v-model="signup_user.newsletter"
                color="secondary"
                :label="$t('signup.newsletter')"
            />
            <q-btn color="primary" class="q-py-sm" type="submit">{{
                $t("signup.get_started")
            }}</q-btn>
        </q-form>
        <div class="row q-my-sm q-mt-md fill">
            <AVLoginModal @on-open="handleOpen" />
        </div>
        <!-- <AVSeperator text="or" /> -->
        <!-- <AVSocialMediaButtons class="q-mt-md" /> -->
    </AVModal>
</template>

<script setup>
import { ref, nextTick } from "vue";
import AVModal from "../atoms/AVModal.vue";
// import AVSeperator from "../atoms/AVSeperator.vue";
// import AVSocialMediaButtons from "../atoms/AVSocialMediaButtons.vue";
import AVLoginModal from "./LoginModal.vue";
import { useAuth } from "../../composables/useAuth";

const modal = ref(false);
const handleOpen = () => {
    nextTick(() => (modal.value = false));
};
const { signUp, signup_user } = useAuth();
</script>

Login Modal:

<template>
    <AVModal
        :title="$t('login.welcome_back')"
        :button-text="$t('signup.login_instead')"
        classes="hide-icon q-mt-sm fit"
        color="blue"
        modal-style="width: 350px"
        v-model="modal"
        @on-open="emit('on-open')"
    >
        <q-form
            @submit="login(login_user)"
            class="row column fitq-gutter-md q-gutter-md"
        >
            <q-input
                outlined
                v-model="login_user.email"
                type="email"
                :label="$t('signup.email')"
            >
                <template v-slot:append>
                    <q-icon name="email" color="grey" />
                </template>
            </q-input>
            <q-input
                outlined
                v-model="login_user.password"
                type="password"
                :label="$t('signup.password')"
            >
                <template v-slot:append>
                    <q-icon name="lock" color="grey" />
                </template>
            </q-input>
            <q-btn color="primary" class="q-py-sm" type="submit">{{
                $t("login.login")
            }}</q-btn>
        </q-form>
        <!-- <AVSeperator text="or" class="q-my-md" /> -->
        <!-- <AVSocialMediaButtons class="q-mt-md" /> -->
    </AVModal>
</template>

<script setup>
import { ref, defineEmits } from "vue";
import { useAuth } from "../../composables/useAuth";
import AVModal from "../atoms/AVModal.vue";
// import AVSeperator from "../atoms/AVSeperator.vue";
// import AVSocialMediaButtons from "../atoms/AVSocialMediaButtons.vue";
const modal = ref(false);
const emit = defineEmits(["on-open"]);
const { login_user, login } = useAuth();
</script>


Maybe my design is bad? Is there a more conventional way of creating modals in Quasar?

Dynamic Chart on Popover Error – Cannot Acquire Context

I am trying to create a chart js popover but I am getting the error:

Failed to create chart: can’t acquire context from the given item

I think that this is probably happening because the canvas tag is created dynamically, but I am not sure how to fix it. Any ideas? This is the js code I am using:

        $(function() {
          $('[data-toggle="popover"]').popover({
            html: true,
            content: '<canvas id="myChart" width="400" height="400"></canvas>',
          }).on('shown.bs.popover', function() {

            const myChart = new Chart("#myChart", {
              // The type of chart we want to create
              type: 'line',

              // The data for our dataset
              data: {
                labels: ["January", "February", "March", "April", "May", "June", "July"],
                datasets: [{
                  label: "My First dataset",
                  backgroundColor: 'rgb(255, 99, 132)',
                  borderColor: 'rgb(255, 99, 132)',
                  data: [0, 10, 5, 2, 20, 30, 45],
                }]
              },

              // Configuration options go here
              options: {}
            });
          });

How to make [i] dynamic using jquery?

I have a list there is an array in each list, Now I’m trying to make array [i] dynamic this is not working. How to solve it?

My Code:-

 for (let i = 0; i < result.result.length; i++) {
                            $.each(result.result[i].services, function(key, value) {
                                serviceList += `<li>${value.name}</li>`;
                            });
                        }

ThankYou for your support!