I know I can’t use if-else statement in JSX but I want to know why

I’m following React’s official document. I’m currently on this topic called conditional rendering, it doesn’t explicitly state that one can’t use if-else statement in JSX but I tried and found it doesn’t work.

I wanted to know why so I Googled it and found some webpages that explains but most of them just say ‘JSX is just syntactic sugar for function calls and object construction.’

I assume that it’s because if-statement is a ‘statement’, not an ‘expression’ and JSX only takes expressions but not sure if I’m right.

Unknown problem compiling/rendering with React Hooks/Context

I’ve developed a website with React where I’m fetching data from a JSON file inside a Context component:

import { createContext, useContext, useState, useEffect } from "react";

const LanguageContext = createContext(undefined)

export const LanguageProvider = ({ children }) => {
    const [language, setLanguage] = useState('ES');

    const updateLanguage = e => setLanguage(e.target.value)

    const [text, setText] = useState({}); 

    useEffect(() => { 
        fetch(`https://raw.githubusercontent.com/julenclarke/ejtos-react_budget_app/main/languagesdata.json`) 
          .then((response) => response.json()) 
          .then((jsonData) => setText(jsonData))
          .catch((error) => console.log(error)); 
      }, []); 

    return (
        <LanguageContext.Provider
            value={{
                language,
                updateLanguage: updateLanguage,
                text
            }}
        >
            {children}
        </LanguageContext.Provider>
    )
}

export const useLanguage = () => useContext(LanguageContext);

And then I call to that data from another component:

import {Link} from 'react-router-dom';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
import { useLanguage } from './LanguageContext';

function Header() {
    const { language, updateLanguage, text } = useLanguage();

    return (
        <div className="header">
            <div className="header-logo">
              <Link to="/" className="nav-item">
                <img width={300} src={require("../assets/img/julenclarkelogo.png")} alt="Julen Clarke logo" />
              </Link>
            </div>
            <div className="header-links">
                {/* <!-- divs in reverse order because of flex-direction: row-reverse; --> */}
                 <div className="language-picker">
                    <FormControl variant="standard" sx={{ m: 1, minWidth: 40 }}>
                        <Select
                            labelId="demo-simple-select-standard-label"
                            id="demo-simple-select-standard"
                            value={language}
                            onChange={updateLanguage}
                            label="ES"
                        >
                            <MenuItem value={'ES'}>ES</MenuItem>
                            <MenuItem value={'EU'}>EU</MenuItem>
                            <MenuItem value={'EN'}>EN</MenuItem>
                        </Select>
                    </FormControl>
                </div> 
                <div className="header-nav-list">
                    <ul>
                        <li><Link to="/videos" className="nav-item">{text[language].videos}</Link></li>
                        <li><Link to="/photos" className="nav-item">{text[language].photos}</Link></li>
                        <li><Link to="/cv" className="nav-item">{text[language].cv}</Link></li>
                        <li><Link to="/press" className="nav-item">{text[language].press}</Link></li>
                        <li><Link to="/contact" className="nav-item">{text[language].contact}</Link></li>
                    </ul>
                </div>
            </div>
        </div>
    );
}

export default Header;

Where depending on the value of the language I extract a different piece of data from the JSON file already mentioned:

{
    "EU": {
        "videos": "Bideoak",
        "photos": "Argazkiak"
    },
    "ES": {
        "videos": "Vídeos",
        "photos": "Fotos"
    },
    "EN": {
        "videos": "Videos",
        "photos": "Photos"
    }
}

My problem is that I’m getting the following error when compiling:

ERROR
Cannot read properties of undefined (reading 'videos')
TypeError: Cannot read properties of undefined (reading 'videos')
    at Header (http://localhost:3000/static/js/bundle.js:2800:40)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:48914:22)
    at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:52200:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:53496:20)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:38506:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:38550:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:38607:35)
    at beginWork$1 (http://localhost:3000/static/js/bundle.js:58481:11)
    at performUnitOfWork (http://localhost:3000/static/js/bundle.js:57728:16)
    at workLoopSync (http://localhost:3000/static/js/bundle.js:57651:9)

I don’t know why it says ‘videos’ is undefined because if I make the changes after compiling it kind of works the way I want, so I suspect it might have to do something with the rendering. However, the compilation error description is referring to compilation files to which I’m not familiar at all.

svg variable height rect with rows of horizontally centered text

See attached image – How do I center align all the text in the blue rect? I’ve done it by eye so far, using x, but in real life I won’t be able to do this as the text lengths will vary. The original rectangle was drawn in Inkscape.

image showing svg  with rectangle and text

The svg:

<g
  id="g2450">
  <rect
    width="30"
    height="40"
    stroke="#00ffff"
    fill-opacity="0"
    id="sensor-info"
  >
  </rect>
  <g
    id="sensor-info-text"
 transform="matrix(0.51584178,0,0,0.51641502,11.648419,22.062229)" 
  />
</g>

I then append the following in javascript:

let s = document.getElementById ('sensor-info-text');
s.innerHTML = `
  <text
    x="-20" y="-20"
    font-family="Verdana"
    font-size="12px"
    fill="#0000ff">
    <tspan >${sensor.Name}</tspan>
    <tspan x="-5" dy="20px" >${sensor.SetPoint + String.fromCharCode(176) + 'C'}</tspan>
    <tspan x="-5" dy="20px">${sensor.Measurement + String.fromCharCode(176) + 'C'}</tspan>
  </text>
`

I’ve tried svg text {dominant-baseline:middle;text-anchor:middle;} in the css, as suggested here: https://stackoverflow.com/questions/5546346/how-to-place-and-center-text-in-an-svg-rectangle, but the text “flies off” to the right if I unset e.g. x.

How do I proceed?

SImply create fade transition between pages

First of all, please note that I’m pretty new to coding.
I’m trying to create a simple fade to transition between my website’s pages. I want the content from the first page to fade out, and the content from the new one to fade in.

I found that solution that seemed to work: How to do transition effects between two html pages

It involves replacing all
<a href="destination.html">Click</a> by <span onclick="transitionToPage('destination.html')" class="internal-link">Click</span>

So I wanted to know if that impacts the SEO, performance or accessibility in any way ?

Thanks!

Python sending GET request to express server in electron main.js process error

I am using the electron framework with a few helper python files. I am running into this error where it seems like I’m unable to start an express server in the main.js process for some reason.

Here is the error

Uncaught Error: listen EADDRINUSE: address already in use :::33333
at __node_internal_captureLargerStackTrace (node:internal/errors:490:5)
at __node_internal_uvExceptionWithHostPort (node:internal/errors:589:12)
at Server.setupListenHandle [as _listen2] (node:net:1740:16)
at listenInCluster (node:net:1788:12)
at Server.listen (node:net:1876:7)
at Function.listen (C:Usersjohndoestuffnode_modulesexpresslibapplication.js:635:24)
at main.js:18:10

Here is the main.js code that is starting the express server

// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, dialog} = require('electron')
const path = require('path');
const { electron } = require('process');
const $ = require('jquery');
const fs = require('fs');
const { Console } = require('console');

const express = require("express")
const expresso = express();
const port = 33333;

expresso.get('/invokeFunction', (req, res) => {
  myFunction(); // this is the function you want to invoke
  res.send('Function invoked!');
});

expresso.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

function myFunction() {
  console.log("Function in Electron's main.js has been triggered.");
}

and here is where I’m invoking this function from another file

# testing communication between processes
import requests

response = requests.get('http://localhost:33333/invokeFunction')

This port is 1000% not in use and I’ve checked it using netstat and ensured that connections were being closed when the program stopped running.

Proper guideline for how to use html tag

How do we give image as logo for title bar ?

I tried a image as logo for title as bar ,i used link tag to implemnt image, i also gave proper path to implement that image,but i couldn’t do this .please help me to overcome this problem.

Is it possible to move part of AJAX, jQUERY script from one theme to another Woocommerce?

There are two themes.

  1. Botiga theme (botiga starter template)
  2. OceanWP

The essence of the problem. When I add a script

add_action( 'wp_footer', 'cart_update_qty_script' );

function cart_update_qty_script() {
    if (is_cart()) :
    ?>
    <script type="text/javascript">
        jQuery('div.woocommerce').on('change', '.qty', function(){
        jQuery("[name='update_cart']").removeAttr("disabled").trigger("click");
        });
    </script>
    <?php
    endif;
}

Then on the “cart” page, when increasing or decreasing the number of goods, the page is updated without reloading using jQUERY (or AJAX I don’t know about it). And the cost of the goods is recalculated.

But there is a problem.

In the Botiga theme – the number of goods in the mini cart does not change
enter image description here

And in the OceanWP theme – everything is changing and working out perfectly.

In the Storefront theme, by the way, it also does not work ….

Is it possible to somehow pull out these missing scripts from OceanWP and inject into the Botiga theme? Or Storefront… it doesn’t matter.

P.S.
I have a draft and curve site. Right now I have activated the OceanWP theme. ISSUE

Maybe someone experienced can say what, where and for what it is responsible so that this unfortunate drop at the mini-basket comes to life and begins to be updated?

Styling with JavaScript

I want to get the height of the div tag with javascript, but I ran into a problem, when I define the height in the css file, the javascript does not show me anything, but when I style it in the html itself, it shows me the height value, of course, this is only for the height. It is not like this, it is like this for all properties

Can’t get Electron to work with React router

I have an electron app that uses React.

I use react-router-dom to route different windows to different components –

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
    <React.StrictMode>
        <HashRouter>
            <Routes>
                <Route path='/' element={<App />} />
                <Route path='add' element={<LinkDialog/>} />
                <Route path='modify' element={<LinkDialog/>} />
                <Route path='edit' element={<EditDialog />} />
            </Routes>
        </HashRouter>
    </React.StrictMode>
)

To load each route on each window I use something like this:

const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
process.env.DIST = path.join(__dirname, '../dist')
const loadRoute = (window, route) => {
    if (VITE_DEV_SERVER_URL) {
        const url = new URL(VITE_DEV_SERVER_URL)
        url.pathname = route
        window.loadURL(url.href)
    } else {
        window.loadFile(path.join(process.env.DIST, '../renderer/index.html'), { hash: route })
    }
}

When I’m debugging my code I use BrowserRouter and the pages show properly, but when build the app (And of course switch to HashRouter the pages won’t render, and I can’t figure out what I’m doing wrong.

Also, how can I switch the Router type automatically so I won’t have to do it when changing between build/dev?

Create a dynamic select within the html in fullcalendar

I intend to create a select within the html in the fullcalendar select.

I’ll post my code example:

$(".btn-show").click(function(e) {
  e.preventDefault();
  el = $(this).data('element');
  $(el).show();
  $("section > div").not(el).hide();
});

$(document).on('click', '.dad-visita', function(){
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
          initialViews = 'timeGridWeek';
     }else{
          initialViews = 'timeGridWeek';
     }  

     var calendarEl = document.getElementById('calendario');
     var today = moment().day();

     var calendar = new FullCalendar.Calendar(calendarEl, {
        
        navLinks: true,             
        firstDay: today,
        hiddenDays: [ 0 ],
        initialView: initialViews,
        editable: true,
        selectable: true, 
        unselectAuto:true,
        eventOverlap: false,
        nowIndicator: "true",
        
        select: function(arg) {
            
          $.getJSON('utente.php', function (data) {

                Swal.fire({
                    title: 'NOVA VISITA',
                      showCancelButton: true,
                      confirmButtonText: 'Create',
                    html:
                      '<label for="title" class="col-sm-4 control-label">NOME UTENTE</label>' +
              '<select name="title" class="form-control" id="title">' +
              '<option value=""></option>' +
              for (var i = 0; i < data.length; i++) {
                 codigo = data[i][1];
                 nome = data[i][2];
                 '<option value="${codigo}">${nome}</option>' +
              }
              '<input id="eventtitle" class="swal2-input" placeholder="Event name" style="width: 84%;"  >',
                    focusConfirm: false,
                    preConfirm: () => {
                        return [
                            document.getElementById('eventtitle').value,
                            document.getElementById('eventdescription').value
                        ]
                    }
                }).then((result) => {
                  
                    
                })

          calendar.unselect()
       });
        }
        
    });

    calendar.render();
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/main.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/main.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/pt-br.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<a href="s160" data-element="#minhaDiv160" class="btn-show dad-visita">
    <i class="metismenu-icon pe-7s-info"></i>
    Consultar Visitas
</a>

<section id="s160">
  <div style="display:none;" id="minhaDiv160">
    <div class="cal-wrapper"><div id='calendario'></div></div>
    <div class="cal-wrapper"><div id='calendario1'></div></div>
  </div>
</section>

But this way it doesn’t work. I want the select to be dynamic, to fetch existing data from a database table. The problem is that the for is inside the html, I am not able to close the html before the for and open it again after the for. How can I solve this problem?

Ajax – Uncaught RangeError: Maximum call stack size exceeded – without recursivity

The following code (see Fiddle here) throws the stack overflow referred to in the question title.

      $.ajax({
            type: "post", // "post" "get" "delete" "put"
            data: data, // PREFERIBLEMENTE JSON
            cache: false,
            headers: {
              "X-CSRFToken": Cookies.get("csrftoken")
            },
            success: function () {
              console.log("response")
              console.log(response)
              $(response).each(function (index, service) {
                $("#dropdown-services").append(`
                  <li class="list-group-item">
                    <div class="row">
                      <div class="col">
                        <label for="service_radio_${ service.id }" class="service-name">
                          ${ service.name }
                        </label>
                      </div>
                      <div class="col-3 d-none">$${ service.price }</div>
                      <div class="col-1 text-end">
                        <input class="form-check-input" type="checkbox" name="service" id="service_radio_${ service.id }"
                          value="${ service.id }" onchange="showServices(this);">
                        <label class="form-check-label" for="service_radio_${ service.id }"></label>
                      </div>
                    </div>
                  </li>
                `)
              })
            },
          });

Uncaught RangeError: Maximum call stack size exceeded

I dont know why this error appears

Use multiple replace

function trimStarsOff(strWithStars) {
    var returnStr = strWithStars.replace(/*/g, '');
    return returnStr.trim();
}

var test = trimStarsOff("This is test ** ");

The result:
This is test

If you want to replace multiple characters, you have to use regex with g flag.
/*/g

And in order to delete space, you can use trim function.

Open-source text embeddings models that can be used locally in Javascript

Is there an open-source model I can download and use locally for creating text embeddings in Javascript? Something like the word2vec npm package, but for paragraphs, not words.

The goal would be something like the LangChain examples, i.e.

import { OpenAIEmbeddings } from "langchain/embeddings/openai";

// Create instance
const embeddings = new OpenAIEmbeddings();

// Create embeddings
const res = await embeddings.embedQuery("Hello world");

but with a local model hosted in the client-side code, instead of an API call to OpenAI or Google, etc.

Ideally it could be called like

const embeddings = readFromLocalEmbeddingsModel(modelFilepath);

Low Video Frame Rate In Chrome and Other Browsers

I am experiencing major frame drops for a video within chrome and other browsers like Firefox. For some reason, Safari seems to not be effected at all.

The video is an MP4 (H.254) at 24fps. The dimensions of the video are 1920×1080

I tried optimizing my JS code (I am new so there is probably much more to be done!). I also tried to increase the frame rate of the video (24 should appear somewhat smooth though) and still got the same lag.

var windowHeight = $(window).height();
var documentHeight = $(document).height();

      function scrollVideo() {
        var video = document.getElementById('video');
          videoLength = video.duration,
          scrollPosition = $(document).scrollTop();

        video.currentTime =
          scrollPosition / windowHeight - windowHeight *
          videoLength;
      }

      $(window).scroll(function (e) {
        scrollVideo();
      });