How to sum, divide values of multiple inputs using onChange event | ReactJS

i try make my first App in react, everything works, but i try take amoun of bill and number of people and divide te bill for person, and add Tip. I know for somebody probably its 5 min solution but i start working with that yesterday and still can’t find solution.

I wanna take bill amount and divide by personAmount + tip if somebody choose tip. What i do wrong

import React, { useState } from 'react'
import style from './BillSplitter.module.css'

const tips = [5, 10, 15, 25]



const Input = ({ label, id, handleChange, name, type, placeholder }) => (
  <>
    <label className={`${style.label}`} htmlFor={id}>{label}</label>
    <input className={`${style.input}`} type={type || "number"} id={id} name={name || id} placeholder={placeholder} onChange={handleChange}></input>
    <br />
  </>
);

const SelectTip = ({ tip }) => {
  <>
    <button className='tipButton' value={tip}></button>
  </>
}

function BillSplitter() {
  const [tipAmount, setTipAmount] = useState(0)
  const [billAmount, setBillAmount] = useState(0)
  const [personAmount, setPersonAmount] = useState(0)


  function handleChange(e) {
    console.log(e.target.value)
  }



  return (
    <div className={`${style.wrapper}`}>
      <div className={`${style.box}`}>
        <div className={`${style.top}`}>
          <h2 className={`${style.title}`}>Bill Splitter</h2>
          <p className={`${style.personBillAmount}`}>Person Bill Amount</p>
          <p onChange={handleChange} className={`${style.totalPersonAmount}`} >$ {tipAmount}</p>
        </div>
        <div className={`${style.bottom}`}>

          <Input handleChange={handleChange} className={`${style.clases}`} placeholder='Amount of bill' label="Bill value">{billAmount}</Input>

          <Input handleChange={handleChange} className={`${style.clases}`} placeholder='Number of people' label="Number of people">{personAmount}</Input>

          <div className={`${style.tipBox}`}>
            <p>Select tip</p>
            {tips.map((tip) => {
              return <button className={`${style.tipButton}`}>{tip} %</button>
            })}
          </div>
        </div>
      </div>
    </div>


  )
}


export default BillSplitter

Pushing array with useState()

Everyone! i just have this kind of problem that i can`t fix.

this is my App.js

import { useState } from "react"
import Header from "./components/header"
import FeedbackList from "./components/FeedbackList"
import FeedbackData from "./data/FeedbackData"

function App() {

    const [feedback, setFeedback] = useState(FeedbackData)

    return (
        <>
        <Header />
        <div className="container">
            <FeedbackList feedback={feedback} />
        </div>
        </>
    ) }

    
    export default App

and this is my second js file that i want to use “feedback” prop like array

import FeedbackItem from "./FeedbackItem"
import FeedbackData from "../data/FeedbackData"
function FeedbackList(feedback) {

return (
    <div>
        {feedback.map((item)=>(
            <FeedbackItem key={item.id} item={item}/>
        ))}
    </div>
  )
}

i cant use feedback.map function in this case because feedback is not like array (sorry for my bad english) i solve this problem without using hooks but i want to know what i can do in this case,sorry if im writing something wrong im just new in React and trying to learn.

Add a progress bar for each card

im new on PHP and Javascript, im coding some timers displayed on cards with PHP. For each card on the screen i need add a timer and a progress bar. So, i already have the timers and the progressbar

i was looking a way to make the progressbar

and i code something like this

<progress class="timer1" value="0" max="100">
</progress> 
<script>
            var ar;
             $(document).ready(function(){
               var _sI=[];
               $.ii=function(){
                 ar=arguments;
                 if(ar.length==3){
                   if(_sI[ar[0]]==undefined){
                     _sI[ar[0]]={};
                     }else{
                       clearInterval(_sI[ar[0]].reg);
                       } _sI[ar[0]].fn=ar[2];
                       _sI[ar[0]].t=ar[1];
                       _sI[ar[0]].reg=setInterval(ar[2],ar[1]);
                       }else if(ar.length==1){
                         clearInterval(_sI[ar[0]].reg);
                         }}});
            $(document).ready(function () {
                  var value = localStorage.getItem("timer1_value") || 0;
                  $('.timer1').val(value);
                  $.ii('t1', 36000, function () {
                      var t1v = $('.timer1').val();
                      if (t1v < 100) {
                          $('.timer1').val(t1v + 1);
                          localStorage.setItem("timer1_value", t1v + 1)
                      } else {
                          localStorage.removeItem("timer1_value");
                          $.ii('t1');
                      }
                  });
              });
            </script>

and yea, this works for me, except for the progress bar for each element

i bring all my rows on a query and the fetched data (MariaDB Mysql) is something like

$row[0] //ID
$row[1] //serial number
//bla bla bla

i understand that i only need the ID for each element, but i dont know how i can put this on my code… i was thinking something like this

<progress class='<?= timer . $row[0] ?>'  value="0" max="100">
            </progress> 
            <script>
            var ar;
             $(document).ready(function(){
               var _sI=[];
               $.ii=function(){
                 ar=arguments;
                 if(ar.length==3){
                   if(_sI[ar[0]]==undefined){
                     _sI[ar[0]]={};
                     }else{
                       clearInterval(_sI[ar[0]].reg);
                       } _sI[ar[0]].fn=ar[2];
                       _sI[ar[0]].t=ar[1];
                       _sI[ar[0]].reg=setInterval(ar[2],ar[1]);
                       }else if(ar.length==1){
                         clearInterval(_sI[ar[0]].reg);
                         }}});
            $(document).ready(function () {
                  var value = localStorage.getItem("timer1_value") || 0;
                  $('<?= '.' . timer . $row[0] ?>').val(value);
                  $.ii('<?= t . $row[0] ?>', 36000, function () {
                      var t1v = $('<?= '.' . timer . $row[0] ?>').val();
                      if (t1v < 100) {
                          $('<?= '.' . timer . $row[0] ?>').val(t1v + 1);
                          localStorage.setItem('<?= timer . $row[0] . '_value'?>', t1v + 1)
                      } else {
                          localStorage.removeItem('<?= timer . $row[0] . '_value'?>');
                          $.ii('<?= t . $row[0] ?>');
                      }
                  });
              });
            </script>

but this is unsatisfactory about the bars, all displays on the same value of the var

i dont know what i can do D:

Injecting card information to website checkout React Native WebView

I’m working on a project that allows users to pay for items through virtual generated cards. It is built on React Native and uses WebView to allow in-app browsing of online stores. Since there is no native integration with the stores, I wanted to check how I could inject the virtual card details into checkout form through something like button click. The follow-up question would be if such form fields have similar id’s across the online store spectrum – which if not need to be handled (please let me know if I need to inspect each webpage for the id name in such case as I’m fairly new). I’ve attached an example screenshot of a checkout page that I want to test this on. If possible, please provide an example using the following template (an example I found to change website background color):

const jsCode = `document.querySelector('.HeaderHero').style.backgroundColor = 'purple';`;
    return (
      <View style={styles.container}>
        <WebView
          ref={ref => {
            this.webview = ref;
          }}
          source={{ uri: this.state.webViewUrl }}
          originWhitelist={['*']}
          javaScriptEnabledAndroid={true}
          injectedJavaScript={jsCode}
        />
      </View>
    );

Checkout page to inject card information to

Why is my information not presenting to the screen properly

So I can get my account tickets and I can see them in my vue browser application and I can dump them to the page but if I want to be able to mold the information and get just the name or the image attached to the api that I am getting it wont allow me to I have tried everything I can think of. Basically what I am trying to achieve is just get the events that only one user is attending. Any Suggestions

Account Page

<template>
  <div class="about text-end">
    <img class="rounded-pill m-3" :src="account.picture" alt="" />
  </div>
  <section id="account-events">
    <h5>My Events</h5>
    <div id="events-container">
      <div></div>
    </div>
  </section>
  <section id="event-tickets">
    <h5>My Tickets for attending Events</h5>
    <div class="row">
      <!-- <TowerEvent
        v-for="t in towerEvents"
        :key="t.id"
        :towerEvent="t"
        class="col-md-4 selectable"
      /> -->
    </div>
    <div class="row card" v-for="t in towerEvents" :key="t.id">
      {{ towerEvents }}
    </div>
    <div class="events-container"></div>
  </section>
</template>

<script>
import { computed, onMounted } from 'vue'
import { AppState } from '../AppState'
import { accountService } from '../services/AccountService'
import Pop from '../utils/Pop'
import { towerEventsService } from '../services/TowerEventsService'
export default {

  name: 'Account',

  setup(props) {

    onMounted(async () => {
      try {
        await accountService.getMyTickets()
        await towerEventsService.getEvents()
      } catch (error) {
        Pop.error(error)
      }


    })
    return {
      account: computed(() => AppState.account),
      towerEvents: computed(() => AppState.accountTickets),
    }
  }
}
</script>

<style scoped>
img {
  max-width: 100px;
}
</style>

Also Here is my Home Page where I get all events

<template>
  <div class="home container">
    <div class="row card bg-dark rounded mt-4">
      <div class="d-flex justify-content-between col-md-12">
        <h5 class="selectable" @click="towerFilter = ''">All</h5>
        <h5 class="selectable" @click="towerFilter = 'concert'">Concerts</h5>
        <h5 class="selectable" @click="towerFilter = 'convention'">
          Conventions
        </h5>
        <h5 class="selectable" @click="towerFilter = 'sport'">Sports</h5>
        <h5 class="selectable" @click="towerFilter = 'digital'">Digital</h5>
      </div>
    </div>

    <div class="row events-row">
      <TowerEvent
        v-for="t in towerEvents"
        :key="t.id"
        :towerEvent="t"
        class="col-md-4 selectable"
      />
    </div>
  </div>
</template>

<script>
import { computed, onMounted, ref } from '@vue/runtime-core'
import Pop from '../utils/Pop'
import { towerEventsService } from '../services/TowerEventsService'
import { AppState } from '../AppState'
export default {
  name: 'Home',
  setup(props) {
    const towerFilter = ref('')
    onMounted(async () => {
      try {
        await towerEventsService.getEvents()
      } catch (error) {
        Pop.error(error)
      }


    })
    return {
      towerFilter,
      towerEvents: computed(() => AppState.events.filter(e => towerFilter.value ? e.type == towerFilter.value : true)),



    }

  }
}
</script>

<style scoped lang="scss">
</style>

Finally the event component that I am injecting into the my home page

<template>
  <div
    class="event-card card m-1"
    @click="selectTowerEvent"
    :style="`background-image: url(${towerEvent.coverImg});`"
  >
    <!-- this is not my image anymore not is on my background image -->
    <!-- <img class="img-fluid" :src="towerEvent.coverImg" alt="" /> -->
    <div class="text-block">
      <h5>{{ towerEvent.name }}</h5>

      <p>{{ towerEvent.location }}</p>
      <p v-if="towerEvent.startDate">
        {{ formatDate(towerEvent.startDate) }}
      </p>
      <p>{{ towerEvent.type }}</p>
      <div class="text-end">
        <p>{{ towerEvent.capacity }}</p>
      </div>
      <!-- come back to this to fix the sold out tag not working -->
      <div v-if="towerEvent.capacity == 0" class="bg-danger rounded">
        <h6>Sold Out!</h6>
      </div>
      <div v-if="towerEvent.isCanceled == true" class="bg-danger rounded">
        <h6>Cancelled!</h6>
      </div>
    </div>
  </div>
</template>


<script>

import { useRouter } from 'vue-router'

export default {
  props: { towerEvent: { type: Object, required: true } },
  setup(props) {
    const router = useRouter()

    return {

      selectTowerEvent() {
        router.push({ name: 'EventDetails', params: { id: props.towerEvent.id } })
      },


      formatDate(rawDate) {
        let time = new Date(rawDate)
        // let month = new Intl.DateTimeFormat('en-US', { month: 'long' }).format(time)
        let day = time.toDateString()
        // let year = time.getUTCFullYear()
        return ` ${day}`
      }



      // come back later to figure out how to format the date
      // time() {
      // towerEvent.startDate = formatDate.toDateString()

      //  moment().format("MMM DD YY");
    }
  }
}




</script>


<style lang="scss" scoped>
.text-block {
  background-color: black;
  color: white;
  padding-left: 20px;
  padding-right: 20px;
}
</style>

Any help would be wonderful sorry if I posted to much code I am kind of new to coding.

Express JS Middleware Mongoose filter and sort query i dont get what i expect to get and it’s not sorting

this is the middleware to filtre and sort
i tryed to modfie this middleware but it’s not work how i like

 const aliasTopMenu = (req, res, next) => {
  req.query.sort = '-price';
  req.query.fields = 'name,price,rating';
  req.query.limit = '3';
  next();
};

in router file
just passe the middleware before function to get data
express.Route().route(‘/top-5-menu’).get(aliasTopMenu, getAllItems);

getAllItems function :
this function to get all and filter some data as user want

const getAllItems = AsyncWrapper(async (req, res) => {
  //1)filtring

  const qeuryObj = { ...req.query };
  const excludField = ['page', 'sort', 'limit', 'fields'];
  excludField.forEach((el) => {
    delete qeuryObj[el];
  });
  //advanced filtring
  let queryStr = JSON.stringify(qeuryObj);
  queryStr = queryStr.replace(/(gt|gte|lte|lt)/g, (matched) => {
    return `$${matched}`;
  });
  let query = await Item.find(JSON.parse(queryStr));

  //2) sorting

  if (req.query.sort) {
    const sortBy = req.query.sort.split(',').join(' ');
    query = await Item.find(JSON.parse(queryStr)).sort(sortBy);
  }
  //3)Field limiting
  if (req.query.fields) {
    const fields = req.query.fields.split(',').join(' ');

    query = await Item.find(JSON.parse(queryStr)).select(fields);
  }
  //Pagination page and limit
  if (req.query.page) {
    const page = req.query.page * 1 || 1;
    const limit = req.query.limit * 1 || 100;
    const skip = (page - 1) * limit;
    const numItems = await Item.countDocuments();
    if (skip >= numItems) {
      throw new Error('this page do not exist');
    }
    query = await Item.find(JSON.parse(queryStr)).skip(skip).limit(limit);
  }

  //execute query

  const items = await query;

  res.status(200).json(items);
});

resault to this query “{{URL}}/items/top-5-menu” {{URL}} is global variable containe localhost and prot

 [
    {
        "rating": 4.5,
        "_id": "62aa6f0cb6cf327c8c4d219a",
        "name": "Pizza",
        "price": 350
    },
    {
        "rating": 4.5,
        "_id": "62aa6f15b6cf327c8c4d219c",
        "name": "Sawarma",
        "price": 150
    },
    {
        "rating": 4.5,
        "_id": "62acf53798c9c74218de901f",
        "name": "Burger",
        "price": 250
    },
    {
        "rating": 4.5,
        "_id": "62acf56298c9c74218de9021",
        "name": "Pizza",
        "price": 400
    },
    {
        "rating": 4.5,
        "_id": "62ad10569b344b2b223e6ea4",
        "name": "Shawarma",
        "price": 500
    },
    {
        "rating": 4.5,
        "_id": "62ad10709b344b2b223e6ea6",
        "name": "takos",
        "price": 400
    },
    {
        "rating": 4.5,
        "_id": "62ad10769b344b2b223e6ea8",
        "name": "takos",
        "price": 250
    },
    {
        "rating": 4.5,
        "_id": "62ad10839b344b2b223e6eaa",
        "name": "chiken",
        "price": 400
    },
    {
        "rating": 4.5,
        "_id": "62ad108f9b344b2b223e6eac",
        "name": "chiken",
        "price": 350
    },
    {
        "rating": 4.5,
        "_id": "62ad109b9b344b2b223e6eae",
        "name": "chiken",
        "price": 350
    }
]
 

dont sort data by price

Sort full text search results by relevance score in nextapps Flexsearch or alternative

I implemented a simple full text search using Flexsearch by nextapps on Node.js. Relevance based scoring is listed as one of it’s features, but results are returned in chronological order when contextual search is disabled.

  1. Is there a way to sort by some relevance score like TF-IDF?
  2. Is there a way to return a relevance score?
  3. If neither, what would be a good alternative Node.js module for static index and with few dependencies?

How to pass an array object from a component to a page in reactjs

Child

import React from "react";
import { Link } from "react-router-dom";

import "../pages/All.css";

const MovieList = (props) => {
    return(
    <>
        {props.movies.map((movie, index) => (

            <div className="ro">
                <img src={movie.Poster} alt={movie.Title} /> <br /> <br />
                <label>{movie.Title}</label>  <br />
                <p>{movie.Type} {movie.Year}</p> <br /> <br />
                <div className="overlay">
                    <li><Link to = "/play" class="popup-video btn">Watch</Link></li> &nbsp; &nbsp;
                    <li><Link to ="movie-details.html" class="btn">Download</Link></li>
                </div>
            </div>
        ))}
    </>
    );
};

export default MovieList;
import React from "react";
import ReactPlayer from "react-player";

function Play(movie){
    return(
        <div>
             <ReactPlayer width="100%" height="750px" controls url ={"http://www.youtube.com/"+movie.Title} />
        </div>
    );
}


export default Play;

i am trying to pass {movie.Title} to controls url in Parent Component

How to bound variable which I pass through function to a specific parameter

Very stupid question. For example I have a variable data and I have function DoSomething with two parameters par1 and par2. they are both optional parameters that would be null if I pass nothing. But I have only one variable data which I want to bound to the second parameter without touching first parameter. In different language I should write something like DoSomething(par2 = data) or DoSomething(par2: data) but all these examples will raise exception Uncaught SyntaxError: missing ). So what I did wrong?

TypeError: undefined Javascript Vue V-for

I have a function that returns an array of objects like this:

getMonthDaysGrid() {
    const totalLastMonthDays = this.getFirstDayOfMonth().dayNumber;
    const totalDays = this.month.numberOfDays + totalLastMonthDays;
    const monthList = Array.from({ length: totalDays });

    for (let i = totalLastMonthDays; i < totalDays; i++) {
      monthList[i] = {
        date: i - totalLastMonthDays + 1,
        month: this.month.name,
        year: this.month.year,
      };
    }

    return monthList;
  }

when I try to make a v-for div like this:

<div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx">
        <p>
          {{ day.date }}
        </p>
      </div>

this throw me this error:

enter image description here

I can’t figure how to fix it… if it loops the array, how is that I can’t access the object properties?

Use a global state with Context

I’m currently trying to set a globalstate into my app. It’s just about counting points, so a global “score”.
Context seemed easy and I followed some tutorials, but it keeps sending errors.

In my app, I am using React and BrowserRouter to switch between pages.

App.jsx You can see, I tried to wrap with the Store Component

export default function App() {
  return (
    <main>
      <Routes>
        <Store>
          <Route path="/" element={<Welcome />} />
          <Route path="/whoareyou" element={<WhoAreYou />} />
          <Route path="/questionone" element={<QuestionOne />} />
          <Route path="/questiontwo" element={<QuestionTwo />} />
          <Route path="/questionthree" element={<QuestionThree />} />
          <Route path="/result" element={<Result />} />
        </Store>
      </Routes>
    </main>
  );
}

Points.js This is my Context file

import React, { useState, createContext } from "react";

const initialState = { points: 0 };

export const Context = createContext(initialState);

export const Store = ({ children }) => {
  const [state, setState] = useState(initialState);
  return (
    <Context.Provider value={[state, setState]}>{children}</Context.Provider>
  );
};

Component Here is my component, where I want to count a 1 into the “points” Score

export default function WhoAreYou() {
  const [state, setState] = useContext(Context);

  return (
    <StyledSection variant="center">
      <StyledNavLink to="/questionone">
        <StyledButton
          type="button"
          variant="next-button"
          onClick={() => {
            console.log(state.points);
          }}
        >
          NEXT
        </StyledButton>
      </StyledNavLink>
    </StyledSection>
  );
}

Errors

This are the error messages:

undefined is not an object (evaluating ‘element.type.name’)

Warning: React.jsx: type is invalid — expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

Check the render method of App.
App
Router
BrowserRouter


To See the whole code, you can see this CodeSandBox:

https://codesandbox.io/s/empty-https-gpkq0l?file=/src/components/pages/WhoAreYou.jsx:581-1422


I would be very thankful if you guys could help!!

Javascript addeventlistener working without parameters

I was looking for javascript documentation and found this

const log = document.getElementById('log');

document.addEventListener('keydown', logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}

I don’t understand how logkey function is working in addeventlistener . when I press a key, the console prints its code but logkey is not having any parameters in addeventlistener. How did it print e.code ?

React JS Filter a 2D array for empty cells

I´m new to React and just try some different stuff.
For example, i want to remove empty columns / Cells from the 2D array. Tried to start removing columns. I not get it working.

The state:

const [data, setData] = useState([]);

The array look something like that:

[
  [
    value: "---",
    value: "ColumnHeader1",
    value: "ColumnHeader2",
    value: "ColumnHeader3"
  ],
  [
    value: "RowHeader1",
    value: "Value11",
    value: "Value12",
    value: "Value13"
  ],
  [
    value: "RowHeader2",
    value: "Value21",
    value: "Value22",
    value: "Value23"
  ],
]

I tried to do it by using for statement, but i cant just remove empty objects from array. cause of:

property X is non-configurable and can't be deleted

This is my method for now:

function removeEmptyCells() {
    setData(prevState => {
        
        for (let i = 0; i < prevState.length; i++) {
            console.log(prevState[i])

            for (let x = 0; x < prevState[i].length; x++) {
                if (Object.keys(prevState[i][x]).length === 0) {
                    prevState[i].splice(x);
                }
            }

        }
        return prevState;
    })
}

In general i´ve 2 questions:

  1. How would a arrow function looks like?
  2. Why i cant just remove empty objects from array?

Save check box values to firebase

In my form I have several checkboxes. All selected checkbox values should be written in firebase database. However, cannot manipulate the checkboxes. My code does not take the checkbox values. It does not appear on firebase. My form looks like this [![Form][1]][1]
[1]: https://i.stack.imgur.com/8FEN4.png

HTML Code

 <td>
                            <label>
                                <input class="paint" id = "paint" value="Anti-Fungus Paint" type="checkbox" unchecked> Anti-Fungus Paint
                            </label>
                            <label>
                                <input class="paint" id = "paint" value="Emulsion Paint" type="checkbox" unchecked> Emulsion Paint
                            </label>
                            <label>
                                <input class="paint" id = "paint" value="Anti-Corrosive Paint" type="checkbox" unchecked> Anti-Corrosive Paint
                            </label>
                            <label>
                                <input class="paint" id = "paint" value="All in one Paint" type="checkbox" unchecked> All in one Paint
                            </label>
                        </td>

Javasript

document.getElementById('formBid').addEventListener('submit',function(e){
            e.preventDefault();
            var id=Date.now();  //generating a unqiue id
            set(ref(db,'quotes/' + id),{
               paint:document.querySelectorAll('input[id="paint"]:checked'),
              
            });
            alert('Quote Sent To Client');
            formBid.reset();