How to change the Page in React.js

I’m learning React.js and I’m creating a demo.

I have created a Login page. Now I want to develop the functionality that if I’m using admin’s credentials then I should change the current page layout to listing of employees. And if I’m using the employee’s credentials then I should change page to show the details of that employee.

Currently it’s not able to print content after proper login.

App.js

import { useState } from 'react';

import './App.css';
import USER_DATA from './userData';
import AdminPage from './components/Admin';
import EmployeePage from './components/Employee';

function App() {
  let [userEmail, setEmail] = useState('[email protected]'),
    [userPassword, setPassword] = useState('password');

  function handleEmail(event) {
    setEmail(event.target.value);
  }

  function handlePassword(event) {
    setPassword(event.target.value);
  }

  function handleLogin(email, password) {
    for (let user of USER_DATA) {
      if (user.userEmail === email) {
        if (user.password === password) {
          if (user.isAdmin) return <AdminPage />;
          else return <EmployeePage />;
        } else {
          console.log('Password not matched ..... ');
        }
      } else {
        console.log('Email not matched ..... ');
      }
    }
  }

  return (
    <div className='App'>
      <header className='App-header'>
        <p className='P'>Welcome there!</p>
        <div
          id='input-div'
          style={{
            display: 'flex',
            flexDirection: 'column',
            margin: '20px',
            alignContent: 'left',
          }}
        >
          <label>Email</label>
          <input
            type='email'
            id='email'
            onChange={handleEmail}
            placeholder={userEmail}
            // value={userEmail}
            required
          />
          <label>Password</label>
          <input
            type='password'
            id='password'
            onChange={handlePassword}
            // value={userPassword}
            placeholder={userPassword}
            required
          />
        </div>

        <div style={{ display: 'flex', margin: '10px' }}>
          <button
            className='Button'
            onClick={() => handleLogin(userEmail, userPassword)}
          >
            Login
          </button>
          <button className='Button'>Registration</button>
        </div>
      </header>
    </div>
  );
}

export default App;

userData.js

const userData = [
  {
    userId: 1,
    userEmail: '[email protected]',
    password: 'password',
    isAdmin: true,
  },
];

export default userData;

Admin.jsx

export default function AdminPage() {
  return (
    <>
      <p>Admin Login</p>
    </>
  );
}

Thank for in advance.

Divide the SVG semicircle into 3 equal parts

I have a Vue.js application and I need to create a progress bar. I’m using SVG because other options won’t work. How can I divide an SVG semicircle into equal parts? I get a solid line. I tried to manipulate the stroke-dasharray attribute, but it didn’t work.

I need to get this look:

progress-bar

I have achieved this so far

enter

Set which radio button of a group is checked / selected by default in pdf javascript

I am constructing a dialog in pdf javascript, which contains multiple groups of radio buttons.
What i don’t get is how to set a default selection for any one group.
The example i have attached below is shortened to only one radio button group.
I do believe that using a check box for this task would probably be better it is not my decision to make.

var oDlg = {
        result: "cancel",
        DoDialog: function() { return app.execDialog(this); },
       
        complete: false,

        commit: function(dialog) {
            var result = dialog.store();

            this.complete = result["completeTrue"];
        },

        description: {
            name: "ADialog", 
            elements: 
            [ 
                {
                    type: "view",
                    elements:
                    [
                        {
                            type: "view",
                            align_children: "align_row",
                            elements:
                            [
                                {
                                    name: "Is complete?", 
                                    type: "static_text",
                                    char_width: 15,
                                },
                                {
                                    item_id: "completeTrue", 
                                    group_id: "complete", 
                                    type: "radio", char_width: 15,
                                    name: "Yes" 
                                },
                                {
                                    item_id: "completeFalse",
                                    group_id: "complete",
                                    type: "radio",
                                    char_width: 15,
                                    name: "No" },
                            ]
                        },
                    ]
                },
                { type: "ok_cancel", },
            ]
        }
    };

I tried checked and selected in various different ways, and couldn’t get that to work. Googling resulted in me trying this.getField("completed").value = someIndex; which also did nothing.
The expected result is that instead of the “Yes” radio button being selected when the dialog opens, the “No” button is selected.

Required Fields Based on other Field in React, Yup and Formik

I have a problem requiring the account_id field when mode_of_payment has a value.

My code below still doesn’t make the account_id required when mode_of_payment has been filled out. mode_of_payment isn’t a required field but when you fill it out, the account_id should become required

import { array, boolean, object, string } from 'yup';

const validationSchema = object().shape({
  remarks: string().nullable(''),
  remittance_items: array().of(
    object().shape({
      id: string().nullable(),
      mode_of_payment_id: object().shape({
        id: string().nullable(),
        name: string().nullable(),
        with_bank_details: boolean(),
      }),
      account_id: object().shape({
        id: string().when('mode_of_payment_id.id', {
          is: (id) => !!id,
          then: string().required('Select an account'),
          otherwise: string().nullable(),
        }),
        name: string().when('mode_of_payment_id.id', {
          is: (id) => !!id,
          then: string().required(''),
          otherwise: string().nullable(),
        }),
      }),
    })
  ),
});

How to show a tooltip on a toggleButton that’s disabled?

I want to show a tooltip of MUI’s ToggleButton when it is disabled
howerver tooltip works fine when ToggleBUtton is not disabled

for disabled it breaks

 <ToggleButton value={item?.key} aria-label="left aligned" key={item?.key} disabled={true} >
             <Tooltip title="Data Not Available" >
                       <span>{item?.value}</span>
             </Tooltip>
  </ToggleButton> 

I am using MUI- both Tooltip and ToggleBUtton are MUI components
and my project is a react project.

I am importing both components as follows-

import ToggleButton from '@mui/material/ToggleButton';
import Tooltip from '@mui/material/Tooltip';

Swiper JS custom style transformations on init

I have a reviews swiper which appears like a deck of cards for which I need custom transformations.
Target Swiper

I am using following code, the styles are being calculated properly but they do not get applied to the swiper slides.

const reviewSwiper = new Swiper('.reviews-swiper', {
slidesPerView: 1,
spaceBetween: 0,
oneWayMovement: true,
rewind: true,
on: {
    init: function(s) {
        let rotate = -8;
        const width = s.slides[0].clientWidth;
        s.slides.forEach((slide, i) => {
            slide.style.transform = `translate3d(calc(${-width*i}px), calc(0px), calc(0px)) rotateX(0deg) rotateY(0deg) rotateZ(${rotate}deg) scale(1);`;
            console.log(slide.style.transform);
            rotate += 8;
        });
    }
}

});

How to create user-movable objects in a web application

There is an application Fast Report Online Designer, I would like to recreate a publicly available free version of this product with open source for all users, as this is a quite useful tool that would simplify the work of many workers
Question: What ways can you recommend for developing a module with drag-and-drop objects (databands) for a web application?

I’m working on Python, planning to use Django for web development
I’ve already tried to figure out dragg and drow in JS, the concept looks similar to the truth, but it’s too complicated to implement (I’m not strong in JS knowledge)
Please suggest some options for implementation
Thank you!

PS:
Fast Report example:
https://www.fast-report.com:2015/razor/Home/Designer
example screenshot:
enter image description here

Handle js ‘window.resizeTo’ in Microsoft WebView2

I am currently developing a Win32 C++ based WebView2 program.

I am writing this post because I have a question regarding WebView2.

I know that Webview2 API provides a callback that can be handled when calling window.open.
(add_NewWindowRequested and ICoreWebView2NewWindowRequestedEventHandler)

By setting put_Handled(true) in ICoreWebView2NewWindowRequestedEventArgs obtained within the callback, or using put_NewWindow, you can open the WebView2 window that you newly create.

Alternatively, I understand that if the request is not handled, a popup created by the Edge engine itself will be displayed.
(In this case, if you enter window.chrome.webview into that window through developer tools, it will be displayed as undefined.)

Question)
About this question, popups generated by the Edge engine (NewWindowRequested not handled) window.resizeTo works fine.
window.resizeTo does not work on newly created WebView2 windows via NewWindowRequested.

Q1) Is there a way to handle that event?
(Even if I checked with Spy++, no special events(window messsge) are received in the WebView 2 popup I created.)
(It seems that windows created in the Edge engine internally receive events through some means and adjust the window through SetWindowPos.)

Q2) According to Mozilla MDN, for window.resizeTo to work, the window must be opened as a popup(not tab) and as window.open. Is the window opened with NewWindowRequested recognized as a ‘tab’? In this case, is resizeTo not working due to policy?

If there is no other way, try to handle resize natively by calling postMessage in javascript.I’ve been struggling for a long time to find a solution to this problem.

help πŸ™

For pop-ups that open from the Edge engine itself
(e.g. if NewWindowRequested is not handled in WebView2 or window.open is done in Edge browser developer tools) Events like WM_WINDOWPOSCHANGING are raised.
If a pop-up is opened by directly handling NewWindowRequested in WebView2, no special window event occurs.

Uncaught TypeError: XLSX.read is not a function while uploading an Excel File in SAPUI5 application

I am trying to read a .xlsx file in my SAPUI5 application using FileReader api.
My requirement is to read the content of the Excel. For this, I have used xlsx library to read the Excel file content.

Here I already added the library in my project and file is also getting loaded and can be seen in my project structure also available in Networks tab as I checked, before usage of the XLSX object, here is my code. Getting error at line oWorkbook = XLSX.read(aData, { type: ‘array’ })

if (sFile && window.FileReader) {
                let oReader = new FileReader();
                oReader.onload = function (e) {
                    let oArrayBuffer = e.target.result,
                        aData = new Uint8Array(oArrayBuffer),
                        oWorkbook = XLSX.read(aData, { type: 'array' }),
                        sSheetName = oWorkbook.SheetNames[0],
                        sSheet = oWorkbook.Sheets[sSheetName],
                        oExcelData = XLSX.utils.sheet_to_json(sSheet, { header: 1 });
                    if (oExcelData.length < 2) {
                        MessageBox.show(oResourceModel.getText("customerData.upload.emptyMsg"), {
                            icon: MessageBox.Icon.ERROR,
                            title: oResourceModel.getText("messageBox.title.error")
                        });
                    } else if (!this._validateColumns(oExcelData[0])) {
                        MessageBox.show(oResourceModel.getText("customerData.upload.columnsError"), {
                            icon: MessageBox.Icon.ERROR,
                            title: oResourceModel.getText("messageBox.title.error")
                        });
                    } else if (this._validateData(oExcelData)) {
                        this._uploadCustomerData(oExcelData);
                    }
                }.bind(this);
                oReader.readAsArrayBuffer(sFile);
            }

The feature works perfectly on my local system, but when I deploy it to the Development system,
the XLSX object is getting initialized as an empty object, causing the functionality to fail.

I am using “xlsx”: “0.15.1” version

I’m not sure which dependency I might be missing or if there’s a different approach I should consider.

Or is there any other way of initializing the XLSX object as it is not getting self-executed.

I already tried with latest version 0.18.5 still the same issue.
Till xlsx version 0.12.13 the functinality is working fine on both Local and Development system but after this version XLSX object is not getting initialized properly on Dev system but working perfectly on Local system.

Why is axios not adding the base URL to some images [closed]

I have a Vue application and I make requests using axios to a back end. On some pages the base url as specified in the main.js file is added to image urls but on some pages the base url is not added. It’s got nothing to do with the backend as the backend is returning the same data no matter what. So on some pages I have to manually add the base URL which is a problem. Why would axios add the base URL to some requests and others not?

As an example here are two functions that fetch data from a backend:

With this function the base URL is added

const getUserPosts = async () => {
  ready.value = false;
  try {
    const response = await axios.get(`/api/v1/posts/user/${account.id}/`);
    if (response.status == 200) {
      userPosts.value = response.data;
      ready.value = true;
    }
  } catch (error) {
    if (error) {
      console.error(error);
    }
  }
};

here is that data:

images: Array(3) [ {…}, {…}, {…} ]
​​​​​
0: Object { id: 32, image: "/storage/posts/post_22/images/CijVJgTl_400x400.png" }
​​​​​
1: Object { id: 33, image: "/storage/posts/post_22/images/2006030f6a214f3f7b546843e3d9e042.jpg" }
​​​​​
2: Object { id: 34, image: "/storage/posts/post_22/images/2498932a-fbf7-4fbf-a020-26843998a92c-original.png" }
​​​​​
length: 3

With this function the base URL is not added


const getPostsByType = (data, type) => {
  const typeObject = data.find((item) => item.type === type);
  return typeObject ? typeObject.posts : [];
};

const getConnectionPosts = async () => {
  ready.value = false;
  try {
    const response = await axios.get(`/api/v1/posts/user/${account.id}/connections/`);
    if (response.status == 200) {
      friendsPosts.value = getPostsByType(response.data, "friends");
      familyPosts.value = getPostsByType(response.data, "family");
      colleaguePosts.value = getPostsByType(response.data, "colleague");
      ready.value = true;
    }
  } catch (error) {
    if (error) {
      console.error(error);
    }
  }
};

here is that data

images: Array(3) [ {…}, {…}, {…} ]
​​​
0: Object { id: 29, image: "http://localhost:8000/storage/posts/post_16/images/167236-004-AE764A76.jpg" }
​​​
1: Object { id: 30, image: "http://localhost:8000/storage/posts/post_16/images/538376_10151400786633552_91901036_n.jpg" }
​​​
2: Object { id: 31, image: "http://localhost:8000/storage/posts/post_16/images/1898031_10152302839588708_776652840_n.jpg" }
​​​
length: 3

I just console logging the response.data so there is no manipulation of data that comes from the back end.

Any help is appreciated

Calling POST request to create new order on shopify always response 200 instead of 201 Created

When I call in postman with body like below

{
  "order": {
    "line_items": [
      {
        "variant_id": 45350427099363,
        "quantity": 1,
        "price": 20,
        "title": "Testing 321",
        "name": ""
      }
    ],
    "customer": {
      "first_name": "tin",
      "last_name": "lo",
      "email": "[email protected]"
    },
    "billing_address": {
      "first_name": "tin",
      "last_name": "lo",
      "address1": "39b ",
      "phone": "53079023",
      "city": "sham sh",
      "country": "hong ",
      "province": "",
      "zip": "0000"
    },
    "shipping_address": {
      "first_name": "tin",
      "last_name": "lo",
      "address1": "39b ",
      "phone": "53079023",
      "city": "sham sh",
      "country": "hong ",
      "province": "",
      "zip": "0000"
    },
    "email": "[email protected]",
    "financial_status": "paid"
  }
}

The response always 200 with the body is list orders insteads of 201 Created and my body

enter image description here

And here is the log from my code

data: '{"order":{"line_items":[{"variant_id":45350427099363,"quantity":1,"price":20,"title":"Testing 321","name":""}],"customer":{"first_name":"tin","last_name":"lo","email":"[email protected]"},"billing_address":{"first_name":"tin","last_name":"lo","address1":"39b ","phone":"53079023","city":"sham sh","country":"hong ","province":"","zip":"0000"},"shipping_address":{"first_name":"tin","last_name":"lo","address1":"39b ","phone":"53079023","city":"sham sh","country":"hong ","province":"","zip":"0000"},"email":"[email protected]","financial_status":"paid"}}'

It’s missing the id and did not create new order

I’ve tried to create a new order in my client’s store, when i tested in my own store with same scope , it’s still created

pls help me to fix this

How do you retrieving strings sent as json objects from your Node server from client side js?

Essentially, im trying to retrieve “img source” which is basically file path to the imgs: e.g. “assts/imgs/image1.png” (stored on my node server in an array called “photos” as an impromptu database.)
I’m using the following directory structure:

{
root
  β”œβ”€β”€ /assts
  β”‚   β”œβ”€β”€ /imgs         # All img stored here
  β”‚   β”œβ”€β”€ /scrpts
  β”‚   β”‚    └── index.js #client-side js
  β”‚   └── /stls
  β”‚        └── style.css #client side CSS
  β”œβ”€β”€ index.html         
  β”œβ”€β”€ server.js
  β”œβ”€β”€ package.json
}

However, all my attempts thus far in trying to fetch the “img src” it via client-side js has results in error 404.

I’ve tried manually checking the url “http://localhost.8080/photos” but ive only gotten “CANNOT GET/” errors.

This is the client js to fetch the JSON objects:

```
addEventListener('click', async function(event) {
            try {
                let response = await fetch('/photos');
                if (!response.ok) {
                    throw new Error(`${response.status}`);
                }
                let photos = await response.json();
```

And the following is the server js:

```
const express = require("express");
const app = express();

const photos = [
  {"source": "assts/imgs/image1.png"}
];

app.get('/photos', (req, res) => {
    try{ 
        res.json(photos);    
    }
});

app.listen(8080);
```

I’ve tried app.use(express.static((__dirname, 'assts'))); but it doesnt work.

Append and modify a flag onClick to Parent element if same element is present on Child element in react js

I want to modify a disabled flag to parent element which has same Id in child element and create a new array which is selected onClick.

let parent = [
{
    "title": "Create User",
    "id": "1",
    "level": 2,
    "child": [
        {
            "title": "View User",
            "id": "2",
            **"disabled": true,**
            "level": 3
        }
    ]
},
{
    "title": "View User",
    "id": "2",
    "disabled": false,
    "level": 2
},
{
    "title": "Toggle User",
    "id": "3",
    "level": 2,
    "child": [
        {
            "title": "View User",
            "id": "2",
            "disabled": true,
            "level": 3
        }
    ]
}

]

Lets suppose,

  1. I selected View User which is having id:”2″ only and nothing else. Disabled flag is “false” So it should allow to select
  2. I selected Create User with Id “1”, So child element also gets selected and Same id in level2 should be marked as disabled true. Because if user having create permission then it must have view permission.
  3. Again if user deselect Create user then parent element with view should be false, so that user can remove view permission.

I tried below code but it is working for Point 1, 2 but 3 is not working.

Note, currentItemId = “1” (Create User)
tempSubId = “2” (View User)

const updateProperty = (**parent**, currentItemId, tempSubId) => {
**parent**.forEach((item) => {
  if(tempSubId === item.id){
    item["disabled"] = !item.disabled
   }
  }
})

}

Any help would be appreciated.

Can I use a custom Image with lat/long instead of x/y in arcGIS (Javascript SDK)? Can I use a custom Image with WebMercator spatialReference?

I’m using ImageElement and MediaLayer, such as in this example:
https://developers.arcgis.com/javascript/latest/sample-code/sandbox/?sample=sketch-3d

to upload a png as the map. In the example, they use x and y coordinates. I’m wondering if it’s possible to integrate latitude and longitude into the image instead?

If it’s not possible to use lat/long instead, are there util functions available to convert x/y to lat/long for different spatialReferences? The only one I could find was in WebMercatorUtils (but I don’t think I’m able to use WebMercator with an image/ImageElement)… which leads me to my next question:

Also, is it possible to upload my own image/ use ImageElement with the WebMercator spatialReference? When I set the spatialReference to WebMercator, my custom image disappears and I see a round globe with no map/images, which I guess would make sense since WebMercator is for a round globe..

If it’s not possible to use WebMercator with my own image/ImageElement, is there an easy way to convert points between 2 different coordinate systems? I think the one in this example uses NAD1927 lat/long (wkid 4267)

Thanks so much for the help!

webkitSpeechRecognition won’t capture audio played in front of a mic in the Google Chrome browser

I am using webkitSpeechRecognition in the browser. I can get speech-to-text when I talk directly on a mic. But it won’t work if I play audio in front of a mic in the Google Chrome browser. At the same time, it works on Microsoft’s edge. So, do you have a solution to capture audio played over a mic and get speech-to-text in the Google Chrome browser?

I tried all settings. But Goole chrome wont captures played audio file to get speech-to-text.