JavaScript module system and React Components

Consider the following simple react app component which is in its own file, App.js and the App component function is exported as default and then imported to main.js file. My question is that why the code other then the App function executes in this file either that be imports or console.log(‘outside function’). Shouldn’t only the code of function should execute when we refer this component in main.js?

import Alexa from './alexa.png';
import Siri from './siri.png';
import Cortana from './cortana.png';

console.log(Siri);
console.log(Alexa);
console.log(Cortana);

export default function App() {
  return (
    <div>
      <h1>Hello, React world!!!</h1>
      <img src={Alexa} alt='' />
      <img src={Siri} alt='' />
      <img src={Cortana} alt='' />
    </div>
  )
}

How to drag and drop table columns in react js?

I trying to make table columns change order by drag and drop , i tried a lot of libraries and the best i could do is this :

import React, { useState } from 'react';
import './list_de_tournees.css'
const Table = ({ columns }) => {
  const [currentColumns, setCurrentColumns] = useState(columns);

  const handleDragStart = (e, columnIndex) => {
    e.dataTransfer.setData('columnIndex', columnIndex);
  };

  const handleDragOver = (e, columnIndex) => {
    e.preventDefault();
    const dragIndex = e.dataTransfer.getData('columnIndex');
    if (dragIndex !== columnIndex) {
      const newColumns = [...currentColumns];
      const [draggedColumn] = newColumns.splice(dragIndex, 1);
      newColumns.splice(columnIndex, 0, draggedColumn);
      setCurrentColumns(newColumns);
    }
  };

  return (
    <table>
      <thead>
        <tr>
          {currentColumns.map((column, index) => (
            <th
              key={column.id}
              draggable
              onDr
              onDragStart={(e) => handleDragStart(e, index)}
              onDragOver={(e) => handleDragOver(e, index)}
            >
              {column.Header}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        <tr>
          {currentColumns.map((column, index) => (
            <td key={column.id}>
              {column.accessor === 'name' && 'alice'}
              {column.accessor === 'age' && '30'}
              {column.accessor === 'country' && 'USA'}
            </td>
          ))}
        </tr>
        <tr>
          {currentColumns.map((column, index) => (
            <td key={column.id}>
              {column.accessor === 'name' && 'Bob'}
              {column.accessor === 'age' && '25'}
              {column.accessor === 'country' && 'Canada'}
            </td>
          ))}
        </tr>
        <tr>
          {currentColumns.map((column, index) => (
            <td key={column.id}>
              {column.accessor === 'name' && 'Charlie'}
              {column.accessor === 'age' && '35'}
              {column.accessor === 'country' && 'UK'}
            </td>
          ))}
        </tr>
      </tbody>
    </table>
  );
};

const columns = [
  {
    Header: 'Name',
    accessor: 'name',
    id: '1',
  },
  {
    Header: 'Age',
    accessor: 'age',
    id: '2',
  },
  {
    Header: 'Country',
    accessor: 'country',
    id: '3',
  },
];

function App() {
  return (
    <div className="App">
      <Table columns={columns} />
    </div>
  );
}

export default App;

but I want it the table to be a static html table and draggable at the same time , i tried this :

  <td draggable onDragStart={(e) => handleDragStart(e, 0)} onDragOver={(e) => handleDragOver(e, 0)}>Alice</td>
    <td draggable onDragStart={(e) => handleDragStart(e, 1)} onDragOver={(e) => handleDragOver(e, 1)}>30</td>
    <td draggable onDragStart={(e) => handleDragStart(e, 2)} onDragOver={(e) => handleDragOver(e, 2)}>USA</td>

but it didn’t work , I couldn’t drag it .
I tried this in simple project of html,css and vanilla js and it work perfectly here example

Is there a way to develop Lasso Selection in Here Maps JS?

I want to develop Lasso Selection on Here Maps.

I had previously made developments for drawing polygons on the map. Simply put, by listening to pointermove and pointerdown events; As the pointer moved, I updated the H.map.Polyline and put an H.map.Marker on the clicked location on the user click event. In the last stage, I placed an H.map.Polygon. You can follow the link for the demo. Polygon Drawing

What I want to do now is the selection method known as Lasso Selection. I don’t know where to start because the lines are not straight in this drawing method. You can also look at this link for the Lasso Selection example. Lasso Example

How can I create a free format(non geometric) drawing like Lasso Selection on Here Maps? Which component can I use in H.map?

Saving to assets in Expo project

So I’m getting into React Expo, and I’m trying to figure out if there’s a way to save to the project folder I’m working in – or accessing one of my assets from the folder and writing to it.

For instance, if I have a ‘someText.txt’ file in my project structure, is there a way to write to that? Or alternatively, a way to generate a text file (or any other file) that gets included in the project folder?

From what I can see you’d usually use the expo-file-system (as found here) for this, but my understanding is that it’s not accessing the files of the project, but rather a different set of folders/files that are under the ‘documentDirectory’ umbrella? So not quite what I’m looking for.

I tried using Node’s “fs” which have the features I’m looking for, it tells me that the React runtime doesn’t include the Node standard library; and from what I’ve searched for, it seems like I need to run node as my backend with react as front-end, if I want to use the Node fs, which kinda defeats the purpose of using Expo

I also tried using React Native’s “fs” module, but that’s not compatable with Expo either

Angular child page refresh redirects to root

The problem regards routing in an Angular 13 app which is divided in few components.
Components hierarchy is something like this:

  • User (root)
    • Child 1
      • Child 1-1
    • Child 2

The root component is under the /u url so it’s renderized when you go to localhost:4200/u. Its html contains a simple menubar which has buttons that redirects to child components (all of them works correctly, no problems at all) and contains a router-outlet so that they can be renderized internally.
The problem comes when I’m, for example, on Child 1-1 and I refresh the page. What happens is that Angular routes to /u/child-1/child1-1 but soon after it routes to /u.
This issue also doesn’t make possible for me to access the app directly from /u/child-1/child-1-1 which is a big problem because I need it.

Routes are configured correctly (otherwise routing from /u to its children wouldn’t work correctly which does) but I’ll report them just in case:

user.route.ts:

const children: Routes = [
  child1Route,
  child2Route,
];

export const USER_ROUTE: Route = {
  path: 'u',
  component: UserComponent,
  data: {
    pageTitle: 'user.title'
  },
  canActivate: [AuthGuard], //disabled
  children: children
};

export const USER_ROUTES: Routes = [USER_ROUTE];
child1.route.ts

const children: Routes = [
  child1-1Route
];

export const child1Route: Route = {
  path: 'child1',
  component: ChildOneComponent,
  children: children
}
child1.route.ts

export const child1-1Route: Route = {
  path: 'child1-1',
  component: ChildOneOneComponent,
}

USER_ROUTE is then inserted into RouterModule.forRoot(USER_ROUTE) in user.module.ts (but again, is not our concern because if roots were bad configured it wouldn’t have worked at all). I didn’t report child2 routes because they are useless for this purpose.

Has anyone ever experienced something like this? How can I understand what is going on?

The only thing I tried succesfully was to listen for url changes in user.component.ts and redirect to /u/child-1/child-1-1 whenever someone went to /u but as you can imagine this is very dirty because I can’t use /u anymore if I do it like this.

why isn’t the JavaScript working on the HTML (bootstrap arrow button)? [duplicate]

I used left and right arrow from bootstrap to my food website. But when I applied javascript leftscroll to the arrow its not working, please help.

HTML code:

 <div class="offers">
        <h5>Coupons & Offers</h5>

        <div class="arrows">

            <i class="bi bi-arrow-left-circle-fill" id="leftscroll"></i>
            <i class="bi bi-arrow-right-circle-fill" id="rightscroll"></i>

        </div>

        <div class="couponsimg">
            <img src="/img/coupon1.png" alt="">
            <img src="img/coupon2.png" alt="">
            <img src="/img/coupon3.png" alt="">
            <img src="/img/coupon4.png" alt="">
            <img src="/img/coupon5.png" alt="">

        </div>
    </div>

JavaScript code:

let rightArrow = document.getElementById('rightscroll')
let couponsimg = document.getElementsByClassName('couponsimg')
let leftArrow = document.getElementById('leftscroll')

rightArrow.addEventListener('click',()=>{
    couponsimg.scrollLeft+=300
})

leftArrow.addEventListener('click',()=>{
    couponsimg.scrollLeft-=300
})

iOS 17 Update Causes Login and Page Responsiveness Issues on Angular Website

We have a website running on Angular/CLI version 11.0.5. On iOS devices running iOS 17, we are encountering an issue where, after logging into our website, the screen becomes unresponsive, and no actions can be performed. The only functionality that remains is scrolling. This issue is specific to iOS 17; everything was working smoothly on iOS 16.6. In the browser console, we are seeing the following errors:

ERROR: TypeError: e.reduceRight is not a function. (In ‘e.reduceRight((e,t)=>new P(e,t),this.backend)’, ‘e.reduceRight’ is undefined)

It’s worth noting that this errors were also present in iOS 16.6, but the website was functioning correctly on those devices. However, in iOS 17, after a page refresh, the user can log in, but all subsequent pages become unresponsive. Before logging in, functions like signup and password reset work as expected.

We are unsure about the changes made in iOS 17 that could be causing this issue.

We have made several attempts to address the issue, particularly by investigating and attempting to resolve the console errors that were initially reported. However, despite our efforts, we have been unable to identify any specific errors in the browser console that appear to be directly related to the problem on iOS 17 devices. This has posed a significant challenge, as we were hoping to pinpoint the root cause of the issue through error messages or debugging information.

At this point, our expectations revolve around finding a solution or workaround for the issue that is causing the login and page responsiveness problems on iOS 17. We are actively seeking assistance and guidance to resolve this compatibility issue and ensure that our Angular website functions seamlessly on iOS 17 devices. Any insights, suggestions, or potential solutions from the community or experts would be greatly appreciated.

how to make the component reusable with custom props with tailwind in vite React

`Hi, I want to make the component reusable by sending customised props for color and size in StarRating component to Star Component. for example [#fcc419] for color or every color or size that user want . I use tailwind in my react project. how can I do that. I test different ways but I was not successful. would you please guide me how to do that?

import { useState } from "react";
import Star from "./Star";

const StarRating = ({
  maxRating = 5,
  textColor = "black",
  starColor = "black",
  textSize = "xs",
  starSize = 5,
}) => {
  const [rating, setRating] = useState(0);
  const [tempRating, setTempRating] = useState(0);

  const onRateHandler = (rate) => {
    setRating(rate);
  };
  const onHoverInHandler = (rate) => {
    setTempRating(rate);
  };
  const onHoverOutHandler = () => {
    setTempRating(0);
  };

  return (
    <div className={`flex flex-row justify-center items-center gap-x-4 p-8 `}>
      <div className="flex flex-row justify-center items-center gap-x-3 ">
        {Array.from({ length: maxRating }, (_, i) => (
          <Star
            key={i}
            onRate={() => onRateHandler(i + 1)}
            full={tempRating ? tempRating >= i + 1 : rating >= i + 1}
            hoverIn={() => onHoverInHandler(i + 1)}
            hoverOut={onHoverOutHandler}
            color={starColor}
            size={starSize}
          />
        ))}
      </div>
      <p className={`text-${textColor} text-${textSize}`}>
        {tempRating || rating || ""}
      </p>
    </div>
  );
};

export default StarRating;
const Star = ({ onRate, full, hoverIn, hoverOut, color, size }) => {
  return (
    <span
      role="button"
      className=" cursor-pointer block "
      onClick={onRate}
      onMouseEnter={hoverIn}
      onMouseLeave={hoverOut}
    >
      {full ? (
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 20 20"
          className={`stroke-${color} fill-${color} w-${size} h-${size} `}
        >
          <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
        </svg>
      ) : (
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 20 20"
          className={`stroke-black fill-none  w-${size} h-${size}`}
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth="{2}"
            d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"
          />
        </svg>
      )}
    </span>
  );
};

export default Star;

I get error when ask PUT or POST request to Firebase RD when sending data javascript

I have a todo list where I want to store the todo tasks in a database under todo. But I get error. I have tried PUT and POST but same error. Why do I get this error? And how can I send data from input field to store in the database?

the error in the console

firebase database

main.js

const form = document.getElementById('form')
const input = document.getElementById('input')
const todosUL = document.getElementById('todos')

const todos = JSON.parse(localStorage.getItem('todos'))
if(todos){
    todos.forEach(todo => addTodo(todo))
}


async function addTodoToFirebase() {
  try {
    const baseURL = 'https://todoparon-default-rtdb.europe-west1.firebasedatabase.app/'
    const url = baseURL + `todo.json`
    const response = await fetch(url)
    let data = await response.json()
    console.log(data)


    // Send the updated data back to Firebase
    const updateResponse = await fetch(url, {
      method: 'PUT', 
      body: input,
      headers: {
        'Content-type': 'application/json; charset=UTF-8',
      },
    });

    if (updateResponse.ok) {
      console.log('Data updated successfully in Firebase!');
    } else {
      console.error('Failed to update data in Firebase.');
    }
  } catch (error) {
    console.error('Error while updating data:', error);
  }
}

form.addEventListener('submit', (e) => {
    e.preventDefault()

    addTodo() 
    addTodoToFirebase()
    
})

How to prevent the line from blocking the port JointJS?

I have an element of this type, the text field here is also a port, because I need the ability to create a connection by dragging any part

example

The problem is that when I start creating a line from the text port, the line runs into the second port

example2

This happens because when a line is drawn, it is rendered lower in the list and has priority above
example3

      defaultLink: () => {
        return new shapes.standard.Link({
          z: -1,
          attrs: {
            line: {
              stroke: "#70F",
              strokeWidth: 2,
              // transform: 'matrix(1, 0, 0, 1, 8, 0)',
              targetMarker: {
                d: null,
              },
            },
            outline: {
              stroke: "#70F",
              strokeWidth: 2,
            },
          }
        });
      }

The Z attribute controls in what order the lines will be rendered after drawing, but not before.
Any ideas on how to make the lines render when drawing above the list or elsewhere? Perhaps somehow I can make it so that there is only one port, but I can also create a line from it when interacting with a text block?

Why am I receving this error? “Cannot read properties of null (reading ‘classList’)”

I’m receiving the error that classList is null on my sliderNav element. I’ve tried setting className and classList.add() and nothing is working. Please help.

const sliderNavDiv = document.createElement('div');
sliderNavDiv.classList.add('slider-nav-div');

for (let j = 0; j < 5; j++){
  const sliderNav = document.createElement('div');
  sliderNav.className = j === 0 ? 'slider-nav active' : 'slider-nav';
  sliderNav.id = j;
  sliderNavDiv.appendChild(sliderNav);

  sliderNav.addEventListener('click', (event) => {
    const id = event.target.id;
    const currentActive = document.querySelector('div.active');

    if (event.target !== currentActive) {
      currentActive.classList.toggle('active');

    if (id > currentActive.id) {
      event.target.classList.toggle('active');
      imageDiv.style.transform = `translateX(-420px)`;
    } else if (currentActive.id > id) {
      event.target.classList.toggle('active');
      imageDiv.style.transform = 'translateX('+`${(currentActive.id - id) * 420}`+'p';
    }   
    
  }
})};

I’m using this in the exact same way elsewhere in my code:

const animateDisplay = () => {
  const currentActiveImg = document.querySelector('img.active');
  currentActiveImg.classList.toggle('active');
  if (currentActiveImg.id != 4) {
    imageDiv.style.transform = 'translateX(-420px)';
    imageDiv.removeChild(currentActiveImg)

    currentActiveImg.nextElementSibling.classList.toggle('active');
    
  } else {
    imageDiv.style.transform = 'translateX(1680px)';
    currentActiveImg.firstElementChild.classList.toggle('active');
  }
};

WHY IS THIS HAPPENING 🙁

How automate ul and li with javascript?

I got a list which links on every items. I want to automate with javascript following actions :

-Get every items (li) of the list (ul)
-On each items, click on the link (li)
-On each pages where we are after clicking on the li, go back to the previous page (with breadcrumbs) where there is the list

enter image description here

thanks a lot

I dont know how to do this, I am not a developer but this tip would help me a lot. Can you give it to me please?

Can the website set scrollbar position in React?

Can the website set scrollbar position in React?

I want to set the tag with the 75% of horizontal scrollbar when user enter the website.

I wonder if the web do this? And how to do.

I ask for chatgpt but its answer is not work.(It provides something like tableRef.current,table.scrollLeft = table.scrollWidth - table.clientWidth;, )

The code woulb be like this:

const MyComponent = () => {
    return (
        <div
            style={{
                width: '300px',
                overflowX: 'scroll',
                overflowY: 'scroll',
                height: '300px',
            }}
        >
            <table style={{ width: '600px' }}>
                <thead>
                    <tr>
                        <th>Header 1</th>
                        <th>Header 2</th>
                        <th>Header 3</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Row 1, Column 1 - Lorem ipsum dolor sit amet,
                            consectetur adipiscing elit.
                        </td>
                        <td>
                            Row 1, Column 2 - Lorem ipsum dolor sit amet,
                            consectetur adipiscing elit.
                        </td>
                        <td>
                            Row 1, Column 3 - Lorem ipsum dolor sit amet,
                            consectetur adipiscing elit.
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Row 2, Column 1 - Lorem ipsum dolor sit amet,
                            consectetur adipiscing elit.
                        </td>
                        <td>
                            Row 2, Column 2 - Lorem ipsum dolor sit amet,
                            consectetur adipiscing elit.
                        </td>
                        <td>
                            Row 2, Column 3 - Lorem ipsum dolor sit amet,
                            consectetur adipiscing elit.
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    )
}

function App() {
    return (
        <div className='App'>
            <MyComponent />
        </div>
    )
}

export default App

expect is:

enter image description here