How to update state shared between Parent and Child React components within the Parent

I’ve built a simple interface for selecting items from a menu, contained in a component called Sodas, and it’s displayed in the Parent component: VendingMachine.

As it is, Sodas is able to successfully change the state in the VendingMachine, however, the state cannot be changed within the VendingMachine itself.

The following code represents the VendingMachine component:

import Sodas from './Sodas';

const VendingMachine = () =>
{
   // Track selected soda
   const [selectedSoda, setSoda] = useState({ sodaName: '', stock: 0 });

   const handleSodaSelection = (soda) => setSoda(soda);

   // Reset the selected soda
   const sellSoda = () => setSoda({ sodaName: '', stock: 0 });

   return (
   <div>
      Soda to Purchase: {selectedSoda.sodaName}
      <Sodas handleSodaSelection={handleSodaSelection} />
      <div onClick={sellSoda}>Buy Selected Soda</div>
   </div
}

The following code represents the Sodas Component

function Sodas({ handleSodaSelection  })
{
   // Tracks soda selected, and returns to Parent component
    const [sodaSelected, setSodaSelected] = useState({ sodaName: '', stock: 0 });
    React.useEffect(() => handleSodaSelection(sodaSelected), [sodaSelected, handleSodaSelection]);

return (
   <div className='soda_container'>
      <div onClick={() => setSodaSelected({ sodaName: 'Cola', stock: 7 })}>Soda</div>
   </div>)
}

Specifically, the issue is that setSoda does not work within VendingMachine and only works when passed to the Sodas component. I’m not sure if this can only work as a one way relationship or if there is something I’m missing in the syntax.

Any help or references to relevant documentation would be greatly appreciated.

Image is not moving away from cursor

i have a image ,i want whenever cursor try to touch the image it moves away randomly from the cursor i tried using jquery but it not working , see this link http://jsfiddle.net/emreerkan/atNva/

my index.html

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
   


    <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
</head>
<body>

    <img src="https://images.pexels.com/photos/569986/pexels-photo-569986.jpeg?auto=compress&cs=tinysrgb&w=600" width="100" height="100" alt="Grey Square" class="som" />
    
    
</body>
<!-- <script src="jquery-3.6.1.min.js"></script> -->
<script>
    alert('hi')
    jQuery(function($) {
    $('.som').mouseover(function() {
        var dWidth = $(document).width() - 100, // 100 = image width
            dHeight = $(document).height() - 100, // 100 = image height
            nextX = Math.floor(Math.random() * dWidth),
            nextY = Math.floor(Math.random() * dHeight);
        $(this).animate({ left: nextX + 'px', top: nextY + 'px' });
    });
});
</script>
</html>

my style.css

body { position: relative; }
#img { position: relative; }

Cypress Error: connect ETIMEDOUT cy.visit()

I am receiving an abnormal visit error in cypress browser. However if I visit the same url in normal browser, it works. Here is the screenshot of the error.

enter image description here

I’ve tried this:

      cy.visit(this.hrefLink, {
        timeout: 30000, 
        headers: { 
          "Accept-Encoding": "gzip, deflate, br",
          "Accept-Language": "en-US,en;q=0.5",
          "Content-Type": "text/html"
        } 
      });

Getting error when I try to upgrade react-router v5 to V6

I m getting typescript error when I tried to upgraded React-router-dom v5 to v6, How can I fix this typescript error. below you can find the code Thanks in advance

`

export function withRouter(ui: React.ReactElement) {
  const history = useNavigate();
  const routerValues: any = {
    history: undefined,
    location: undefined
  };

  const result = (
    <MemoryRouter>
      {ui}
      <Route
        path="*"
        element={({ history, location }) => {
          routerValues.history = history;
          routerValues.location = location;
          return null;
        }}
      />
    </MemoryRouter>

enter image description here`

below you can find entire file code
`

import React from "react";
import { Reducer } from "@reduxjs/toolkit";
import { Provider } from "react-redux";
import { MemoryRouter, Route, useNavigate } from "react-router-dom";
import buildStore from "../redux/store";

export function withRedux(
  ui: React.ReactElement,
  reducer: {
    [key: string]: Reducer;
  },
  initialState: any
) {
  const store = buildStore(initialState, true);
  const dispatchSpy = jest.spyOn(store, "dispatch");

  return {
    result: <Provider store={store}>{ui}</Provider>,
    store,
    dispatchSpy
  };
}

export function withRouter(ui: React.ReactElement) {
  const history = useNavigate();
  const routerValues: any = {
    history: undefined,
    location: undefined
  };

  const result = (
    <MemoryRouter>
      {ui}
      <Route
        path="*"
        element={({ history, location }) => {
          routerValues.history = history;
          routerValues.location = location;
          return null;
        }}
      />
    </MemoryRouter>
  );

  return { result, routerValues };
}

`

I am passing history and location props which were work fine when I was using react router v5
here is the previous code :
`

const result = (
    <MemoryRouter>
      {ui}
      <Route
        path="*"
        render={({ history, location }) => {
          routerValues.history = history;
          routerValues.location = location;
          return null;
        }}
      />
    </MemoryRouter>

`

After update react router v6 I changed in my code because We know that v6 no longer support render keyword inside route So I Replace it

`

const result = (
    <MemoryRouter>
      {ui}
      <Route
        path="*"
        element={({ history, location }) => {
          routerValues.history = history;
          routerValues.location = location;
          return null;
        }}
      />
    </MemoryRouter>
  );

`

But I don’t have Idea in v6 How can I pass these props inside route

Form validation? make textbox border green/red depending on conditions

How do i make it so the border of the phone number box is green when it follows the format: 123 456 7890 (3 digits, space, 3 digits, space, 4 digits) and red if it does not?

additionally, how do i make it so the product id/product info text box border is green when RW100, RW101, RW102, RW103, RW200, RW201, RW202, or RW203 are entered and red when not?

thank you

https://jsfiddle.net/MangoMelody_/yfv8rcx2/5/

<script>
//product id validation
function idCheck() {
  var prodNameBox = document.getElementById("prodname");
  var prodname = prodNameBox.innerText;
  if (prodname === 'RW100' || prodname === 'RW101' || prodname === 'RW102' || prodname === 'RW103' || prodname === 'RW200' || prodname === 'RW201' || prodname === 'RW202' || prodname === 'RW203') {
    prodNameBox.style.borderColor = "green";
  } else {
    prodNameBox.style.borderColor = "red";
  }
}

// phone number validation
function phoneNumber() {
  var phonenoBox = document.getElementById("phoneno");
  var phoneno = phonenoBox.value;

  if ((phoneno.value.match("^[1-9]d{2}sd{3}sd{4}"))) {
    phonenoBox.style.borderColor = "green";
  } else {
    phonenoBox.style.borderColor = "red";

  }
}
</script>

air-datepicker стили для изменения календаря [closed]

Тяжело менять стили почему то в самом календаре((( К примеру не могу поменять стили названий дней недели…..Они как стоят оранжевыми, так их не поменять

Что только не пробовал, все равно перебивается ваш стиль

Confirmation before closing the browser tab or warn the user on unsaved changes in Next.js?

all I am currently in a process of migrating my existing react application to nextjs. I have a use case where in I want to show a confirmation before the user is trying to close a browser tab or warn the user about unsaved changes. When a user is in the process of filling out an application form and decides to drop out I want to warn him that the stored data will be lost, and for an existing user if he has already signed up and lands on the dashboard and wants to close the tab or wants to go back to a previous route which in this case is signup I want to prompt him to either logout or continue.
Previously I was using CRA and react-router dom v5 and the following is the code that I used to achieve the above results:-

import React, { useEffect, useState } from "react";
import { Prompt } from "react-router-dom";

const useUnsavedUsageWarning = (
  message = "Are you sure you want to discard changes?"
) => {
  const [isDirty, setDirty] = useState(false);

  useEffect(() => {
    // Detecting browser closing
    window.onbeforeunload = isDirty && (() => message);
    return () => {
      window.onbeforeunload = null;
    };
  }, [isDirty]);

  const routerPrompt = <Prompt when={isDirty} message={message} />;

  return [routerPrompt, () => setDirty(true), () => setDirty(false)];
};

export default useUnsavedUsageWarning;

Following is a link to code sandbox for my sample react js example:-
https://codesandbox.io/s/back-handling-react-router-v5-4e9q3m
Any help or support is much appreciated.

Align Widget for Flutter

Using the flutter Align widget, you can quickly align any widget in flutter.

Align(
      alignment: Alignment.center,
      child: Text(
        "ALIGN WIDGET FOR FLUTTER",
        style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
      )),

Why is one ternary statement cancelling out another?

I’m trying to build a set of traffic lights and am currently working on the automated functionality. When I comment out the (sec >= 54) statement, the rest of the program functions as expected – a smooth transition from green to orange to red and back again.

However, with the ‘orange flash’ (sec >= 54) statement active, the (sec >= 26) statement doesn’t work.

let time = new Date();
let sec = time.getSeconds();
const defaultSystem = setInterval(dispSecs, 1000);
function dispSecs() {
    console.log(sec++);
    sec === 60 ? sec = 0 : sec;
    sec < 26 ? greenLight.style.backgroundColor = 'green' : 
            greenLight.style.backgroundColor = 'black';
    sec >= 26 && sec < 29 ? orangeLight.style.backgroundColor = 'orange' :
            orangeLight.style.backgroundColor = 'black';
    sec >= 29 && sec < 54 ? redLight.style.backgroundColor = 'red' :
            redLight.style.backgroundColor = 'black';
    sec >= 54 && sec % 2 === 0 ? orangeLight.style.backgroundColor = 'orange' :
            orangeLight.style.backgroundColor = 'black';
}

I have tried to contain the ‘orange flash’ statement in a while loop. I’ve looked for spelling errors and I have tried commenting out different parts of the code. I have also tried rearranging parts of the code but this just causes different issues. Even with the ‘orange flash’ statement operational, the other lights function as intended. I’m just not getting the still orange between seconds 26 and 29. Any advice is much appreciated. Thanks!

Javascript: make bold () a variable containing a string

Just learning Javascript and can’t find a way to make bold the string a variable holds.
example = ‘house’
document.write(example) prints ‘house’, but not in bold. If I knew that ‘house’ was in example, I could do: document.write(‘house‘);
But example is a variable that could contain anything. I want to print whatever it contains, in bold.
document.write(‘example‘); prints example, not what’s in example. What would print what’s in example, in bold?

Thanks!

How to load a JS library in Blazor server razor file?

I’m trying to follow the document HERE to load THIS bootstrap-datepicker within a blazor server app. Note: I want to load it for a single page only without having to load it for all pages.

Within the .razor file I’m trying to do this:

HTML

<input @ref=ReferenceToInputControl class="form-control" id="obdInput">

Code

@code {
    ElementReference ReferenceToInputControl;
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            jsModule = await JS.InvokeAsync<IJSObjectReference>("import", "./js/bootstrap-datepicker.js");
            await jsModule.InvokeVoidAsync("Datepicker", ReferenceToInputControl);
        }
    }

}

I get an error that “Could not find Datepicker. Datepicker was undefined”.

I’ve read so much information about IIFE and scope and closure and modules but I can’t for the life of me figure out what I need to do with that function so it will load and I can use it to change the input into a calendar.

Click a form button element on page load

I am attempting to:

  1. Click a button element on page load, and;

  2. Make the form invisible

Currently the JS / HTML is:

<iframe src="https://api.leadconnectorhq.com/widget/form/FORMHERE" style="border:none;width:100%;" scrolling="no" id="FORMHERE"></iframe> <script src="https://api.leadconnectorhq.com/js/form_embed.js"></script>

I have tried document.getElementById('watchButton').click but I have no knowledge on where to put it

Or if I should be creatinga whole other JS / HTML element to perform the click

self is not defined error when i am using jodti-react text edior in nextjs project

self is not defined error when i use jodti-react in nextjs project

import React, { useState, useRef, useMemo } from "react";
import Dashborad from "./Dashborad";
import JoditEditor from "jodit-react";
import dynamic from "next/dynamic";

export default function edit() {
  const editor = useRef();
  const [content, setContent] = useState("");

  return (
    <Dashborad>
      <JoditEditor
        ref={editor}
        value={content}
        tabIndex={1} // tabIndex of textarea
        onBlur={(newContent) => setContent(newContent)} // preferred to use only this option to update the content for performance reasons
        onChange={(newContent) => setContent(newContent)}
      />
    </Dashborad>
  );
}

}

how to solve this error ?