JSX is being rendered as Text

I have an API endpoint which returns JSX as data, if I try to render it, the output being rendered is the whole JSX as text, instead of following the tags. How can I fix this?

export function Card({ product }) {
  return data.data.electricity[0].why_us
}

The data attribute after getting it

"why_us": "<ul>rnt<li>Join over 1 million Australians!</li>rnt<li>Freedom to choose the way you pay with flexible billing options.</li>rnt<li>Benefit from no late payment fees, no fees for paper bills, and no credit card fees (including American Express).</li>rnt<li>Access your account online 24/7 with My Account.</li>rnt<li>No lock-in contracts, exit fees or paper bill fees.</li>rnt<li>Gain access to savings and special offers through&nbsp;<a href="https://www.alintaenergy.com.au/nsw/residential/customer-rewards/rewards-shop/" target="_blank">Alinta Energy Rewards</a></li>rnt<li>Save up to 48% on movie tickets with Alinta Energy rewards.</li>rnt<li>Multi-award winning taking out one of the top spots in the 2019 Mozo People&rsquo;s Choice Awards in the Highly Trusted, Most Recommended and Excellent Customer Service categories.</li>rnt<li>Proud Platinum Partner of Cricket Australia and Principal Partner of the Australian Men&rsquo;s Cricket Team.</li>rnt<li>2019 Winner - Canstar Blue&rsquo;s Most Satisfied Business Customers award.</li>rn</ul>",

They output I get after rendering is as shown

enter image description here

How can I solve this error? My way of thinking is that the why_us property returns string, hence JSX returns string to render, if that’s the case, how do I convert the string to JSX?

Map is not working on Object.keys JavaScript

I have a simple code where I have a map in JS. Im iterating over the map keys using Object.keys and then using a map over it to return a new Map. But it is not working and console shows no output. Here is my code

let map1 = new Map();

let newMap = new Map();
map1.set('111020022AS', true);
map1.set('23t2t363114',false);
map1.set('110AI1123333', true);
map1.set('0000111222',false);

console.log('map is', map1);

console.log('Keys are', Object.keys(map1));

newMap = Object.keys(map1).map(key =>(

    {
        label: key, 
        value: map1[key]
    }

    
))
console.log('new map is', newMap);

this is console output

map is Map(4) {'111020022AS' => true, '23t2t363114' => false, '110AI1123333' => true, '0000111222' => false}[[Entries]]0: {"111020022AS" => true}1: {"23t2t363114" => false}2: {"110AI1123333" => true}3: {"0000111222" => false}size: 4[[Prototype]]:

 
Keys are []   length: 0[[Prototype]]: Array(0)
new map is []

I cant understand where I am going wrong. I just want to make a new Custom Map after iteration using map function

How to render thousands of components and not make it laggy when a prop changes in React?

Starting my React journey and trying to figure out how I can improve rendering of hundreds/thousands of components.

Say you have 3 components – App, ColorPicker, and Card.

import { useState } from "react"

function Card({ color }) {
  return (
    <div style={{ backgroundColor: color, height: 300, width: 300, color: '#ffffff' }}>
      {color}
    </div>
  )
}

function ColorPicker({ color, setColor }) {
  return <input type="color" value={color} onChange={(e) => setColor(e.target.value)} />
}

export default function App() {
  const [color, setColor] = useState('#000000')
  const items = [...Array(1000).keys()]

  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2rem' }}>
      <ColorPicker color={color} setColor={setColor} />
      { items.map((i) => <Card key={i} color={color}  />) }
    </div>
  )
}

When you have like 500 items and you change the color, you think it’s good. But if you have like a thousand, you’ll notice the lag.

Is there anything I can improve in this code that will make the rendering smooth?

A document “docx.” on google drive

A document with the format “docx.” was created on google drive. The newly created button, by the script, on the taskbar of the document for activating the script was added. When transferring access rights to the file to another user, the button to run the script is not displayed. Is there a method to display it for all users?

The button for activating the script must be functional for all users with access to the file.

How do I set a background image in a sprite in Java script?

This material is taken from this video: https://www.youtube.com/watch?v=vyqbNFMDRGQ&t=7293s
I am just a novice user of Java script, in this language I took up the development of a simple game in Java script, so that it would be much more interesting in the study. That’s just stuck on moment background image in Sprite. I did exactly the same as shown in the video, but it doesn’t work for me, at first I thought that I used the wrong path to development, but I looked it over ten times, and everything is fine, but the image is still not there. I tried a lot of things on the Internet and found nothing. Can anyone figure this out and tell me how to solve the problem?

classes.js
class Sprite {
    constructor({position, imageScr}) {
        this.position=position
        this.height=150
        this.width=50
        this.image=new Image()
        this.image.scr=imageScr
    }
    draw() {
        c.drawImage(this.image, this.position.x, this.position.y)
    }
    update() {
        this.draw()
    }
//listed below in function animate()
background.update()

index.js
const background=new Sprite({
    position: {
        x: 0,
        y: 0
    },
    imageScr: './img/background.png'
})

autocomplete search not trigger auto fill fo other input fields

I am trying to implement autofill with autocomplete. My form consist of three input fields (UserID, Last Nam and First name)User ID is trigger field and auto complete successfully. But i am trying when I select from auto complete list, it should autofill values in other two fields which are first and last name). When I manually enter User ID, then First last name autofill worked fine, but when I select from list, then no autofill working.

Here is my complete code

    <label>User Id</label>
    <input type = "text" name="user_id"
        id='user_id' class='form-control'
        placeholder='Enter user id'
        onchange="GetDetail(this.value)" value="">
    <div id="countryList"></div>

<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>

<script>

$(document).ready(function() {

    $('#user_id').keyup(function() {
    
        var query = $(this).val();
        
        if (query != '') {
        
            $.ajax({
                url: 'searchCountry.php',
                method: 'POST',
                data: {
                    query: query
                },
                success: function(response) {
                    $('#countryList').fadeIn();
                    $('#countryList').html(response);
                }
            });
        } else {
            $('#countryList').fadeOut();
            $('#countryList').html('');
        }
    });

    $(document).on('click', 'li', function() {
        $('#user_id').val($(this).text());
        $('#countryList').fadeOut();
    });

    $('#addCountryForm').submit(function(event) {
    
        event.preventDefault();
        var user_id = $('#user_id').val();
        
        $.ajax({
            type: 'POST',
            url: 'addCountry.php',
            data: {
                user_id: user_id
            },
            success: function(response) {
                $('#countryList').hide();
                $('#message').html(response).show();
            }
        });
    });
});
</script>

        </div>
    </div>
</div>
    
<div class="row">
    <div class="col-lg-6">
        <div class="form-group">
            <label>First Name:</label>
            <input type="text" name="first_name"
                id="first_name" class="form-control"
                placeholder='First Name'
                value="">
        </div>
    </div>
</div>
    
<div class="row">
    <div class="col-lg-6">
        <div class="form-group">
            <label>Last Name:</label>
            <input type="text" name="last_name"
                id="last_name" class="form-control"
                placeholder='Last Name'
                value="">
        </div>
    </div>
</div>

</div>

<script>

// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(str) {
    if (str.length == 0) {
        document.getElementById("first_name").value = "";
        document.getElementById("last_name").value = "";
        return;
    }
    else {

        // Creates a new XMLHttpRequest object
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {

            // Defines a function to be called when
            // the readyState property changes
            if (this.readyState == 4 &&
                    this.status == 200) {
                
                // Typical action to be performed
                // when the document is ready
                var myObj = JSON.parse(this.responseText);

                // Returns the response data as a
                // string and store this array in
                // a variable assign the value
                // received to first name input field
                
                document.getElementById
                    ("first_name").value = myObj[0];
                
                // Assign the value received to
                // last name input field
                document.getElementById(
                    "last_name").value = myObj[1];
            }
        };

        // xhttp.open("GET", "filename", true);
        xmlhttp.open("GET", "gfg.php?user_id=" + str, true);
        
        // Sends the request to the server
        xmlhttp.send();
    }
}
</script>

Laravel vue 3 issue in JS load

I have facing an problem when i load them home page which is home component then js works fine but when i go to another component then click on home component then js not works fine
here it is my code
this is welcome.blade.php

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Kabira</title>
  <meta name="description" content="Morden Bootstrap HTML5 Template">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" type="{{asset('newtheme/image/x-icon')}}" href="{{asset('newtheme/assets/img/favicon.ico')}}">
    
   <!-- ======= All CSS Plugins here ======== -->
  <link rel="stylesheet" href="{{asset('newtheme/assets/css/plugins/swiper-bundle.min.css')}}">
  <link rel="stylesheet" href="{{asset('newtheme/assets/css/plugins/glightbox.min.css')}}">
  <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&amp;family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&amp;display=swap" rel="stylesheet">

  <!-- Plugin css -->
  <!-- <link rel="stylesheet" href="assets/css/vendor/bootstrap.min.css"> -->
  
  <!-- Custom Style CSS -->
  <link rel="stylesheet" href="{{asset('newtheme/assets/css/style.css')}}">

  @vite('resources/css/app.css')
</head>
<body>
    <div id="app"></div>




    @vite('resources/js/app.js')

    <!-- All Script JS Plugins here  -->
  <!-- <script src="assets/js/vendor/popper.js" defer="defer"></script> -->
  <!-- <script src="assets/js/vendor/bootstrap.min.js" defer="defer"></script> -->

  <script src="{{asset('newtheme/assets/js/plugins/swiper-bundle.min.js')}}" defer="defer"></script>
  <script src="{{asset('newtheme/assets/js/plugins/glightbox.min.js')}}" defer="defer"></script>

  <!-- Customscript js -->
  <script src="{{asset('newtheme/assets/js/script.js')}}" defer="defer"></script>
  
</body>
</html>

this is app.js here i also import assets

import './bootstrap';


import {createApp} from 'vue'

import App from './App.vue';
import router from './routes.js';
import './assets/css/style.css';
import './assets/css/plugins/swiper-bundle.min.css';
import './assets/img/favicon.ico';
import './assets/css/plugins/glightbox.min.css';
import './assets/js/plugins/swiper-bundle.min.js';
import './assets/js/plugins/glightbox.min.js';



createApp(App).use(router).mount("#app")

this image when i load the page
when load page and js works

this comes when i come on home component from other component
when comes from other component

How do I render a htmx response using typing effect in Django just like ChatGPT does?

I’m building a book summarizer app as a personal project with Django and I make API requests to OpenAI. The user enters the book name and author and gets the summary of the book. I’m using htmx for the form submission to avoid page refresh.

I’m rendering the summary in a container/textbox. I want to implement a loader effect as soon as the user clicks on the “Submit” button and when the response is ready, it should be rendered with a typing effect and the container should also increase as the texts being rendered increase by line.

Everything works but the texts don’t get rendered using typing effect as I want and also the loader effect starts loading as soon as I open the page not when the user clicks on the submit button. I guess my problem is in the Javascript code. Thanks in advance!

Here are my codes:

Views.py

from django.shortcuts import render
import os, openai, json 
from django.http import JsonResponse, HttpResponse

openai.api_key = os.get(OPENAI_API_KEY)

# Create your views here.





def index(request):
    result = None
    if request.method == 'POST':
        book_name = request.POST.get('book_name')
        author = request.POST.get('author')
        
        prompt = f'Write a summary of the book titled: {book_name} written by {author}. Please only write if you know about the book if not reply you have no information about it.'
        response = openai.Completion.create(
                    model='text-davinci-003',
                    prompt=prompt,
                    max_tokens=300,
            )
        result = response.choices[0].text
        return JsonResponse({'result': result})
    context = {'result': result}

    return render(request, 'tools/book-summarizer.html', context)

**
html page:**

{% load static %}

<!DOCTYPE html>
<html>
<head>
  <title>Book Summarizer </title>
  <script src="https://unpkg.com/htmx.org@^1.5.0/dist/htmx.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/typed.umd.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Bai+Jamjuree:wght@400;500;600;700&display=swap');

    body{
        padding:0;
        margin: 0;
        font-family: 'Bai Jamjuree';
      }

      
    section{
      padding-right: 20%;
      padding-left: 5%;
    }

    #summary-container {
      border: 1px solid #ccc;
      border-radius: 4px;
      padding: 15px;
      margin-top: 20px;
      height: 35vh;
      width: 100%;
    }

    h1{
      color: orange;
      }
     
  </style>
</head>


<body>

  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
      <a class="navbar-brand" href="{% url 'book_summarizer' %}"><h1><span><img src="{% static 'src/img/learning.png' %}" height="30px"></span> Book Summarizer</h1></a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
          <a class="nav-link active" aria-current="page" href="{% url 'book_summarizer' %}">Home</a>
          <a class="nav-link" href="#">Other Tools</a>
          <a class="nav-link" href="#" tabindex="-1">Contact Developer</a>
        </div>
      </div>
    </div>
  </nav>
  
  
 

<section>
  <p class="text">Created By: <a href="{% url 'home' %}">Collins Awusa</a></p>
    <p class="text"><b>Generate Book Summaries Easily with Our AI Tool</b></p>
   




    <form class="form-group" hx-post="{% url 'book_summarizer' %}" hx-target="#summary-container" hx-swap="innerHTML">
      {% csrf_token %}
      <div class="mb-3">
        <label for="book-name" class="form-label"  >Book name</label>
        <input type="text" class="form-control" id="book-name" name="book_name" placeholder="Enter book name" required>
      </div>
      <div class="mb-3">
        <label for="author" class="form-label">Author</label>
        <input type="text" class="form-control" id="author" name="author" placeholder="Enter author's name" required>
      </div>
      <input type="submit" class="btn btn-primary" value="Submit">
    </form> 
    <br />
    <h6>OUTPUT:</h6>
    <div id="summary-container">
      <div class="spinner-border" role="status">
      <span class="visually-hidden">Loading...</span>
    </div>
  </div>
 </div>

</section>



<!-- <footer class="navbar navbar-expand-lg navbar-light bg-light">
  
</footer> -->

<script>
  var i = 0, text;
  text = "{{result}}";
  function typing(){
    if(i < text.length){
      document.getElementById('summary-container').innerHTML += text.charAt(i);
      i++;
      setTimeout(typing, 50);
      document.getElementById('summary-container').style.height = (i + 1) * 1 + 'px'; // Adjust the height dynamically
    }
  }
  typing();
</script>


  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>

Vuetify combobox – How to filter out and remove wrong entries while typing in vuetify’s combobox

I want to let the users to type and select the items from the combobox. But somehow, if we type anything random and press tab, the combobox is taking that as input and that behaviour is not desired in my case.

 <v-row class="ma-1">
        <v-combobox
          v-model="selectedProperties"
          :items="propertyItems"
          label="Properties"
          :menu-props="{ maxHeight: 195 }"
          multiple
          chips
          closable-chips
          max-height="4"
        ></v-combobox>
      </v-row>

Converting dynamic html content to pdf in React js

Converting HTML content from Jodit editor to pdf, having issues with alignment, links and styling issues.

We have tried with libraries like

html2pdf,
html2canvas,
jspdf,
react-pdf,
html-pdf-make,
react-html-pdf,
markdown-pdf,
react-to-pdf,

and we got a close result in html2pdf library. But there are attachment link issue in the pdf that’s generated.
Used the code to split the dymanic content to PDF for large pages from the link below
https://github.com/eKoopmans/html2pdf.js/issues/311#issuecomment-877571959
Please let us know any suggesstion or approach to solve the issue

locator.waitFor: Target closed in Playwright error even though the “Wait” handled

Im trying to implement Playwright/TS Page Object Model framework for a web app.

So in this case Im automating login successful scenario by asserting user can see the Dashboard text.

But Im getting the following error.

Error: locator.waitFor: Target closed
=========================== logs ===========================
waiting for getByRole('heading', { name: 'Dashboard' }) to be visible
============================================================

   at ../pages/DashboardPage.ts:32

  30 |
  31 |      async isDashboardTxtVisible(){
> 32 |       await this.txtDashboard.waitFor({state: "visible"});
     |                               ^
  33 |        return this.txtDashboard.isVisible();
  34 |     }
  35 | }

    at DashboardPage.isDashboardTxtVisible (/Users/ivit/Desktop/Projects/QA/Playwright/PWPOM_V4/pages/DashboardPage.ts:32:31)
    at /Users/ivit/Desktop/Projects/QA/Playwright/PWPOM_V4/tests/login.spec.ts:8:34

Here is my code.

This is the spec file Im executing(login.spec.ts)

import { test, expect } from '@playwright/test';
import { App } from '../pages/App';

test("Checking whether user can logged in", async({page}) => {
  const app = new App(page);
  await app.LoginPage.visit();
  await app.LoginPage.login("Admin","admin123");
  await expect(app.DashboardPage.isDashboardTxtVisible()).toBeTruthy();
  
});

DashoardPage.ts

import { Locator, Page } from "@playwright/test";

export class DashboardPage {

  readonly page: Page;
 
  readonly lnkLeave: Locator;
  readonly lnkPIM: Locator;
  readonly txtDashboard: Locator;

  
  constructor(page: Page){
    this.page = page;

    this.lnkLeave = page.getByPlaceholder('Username');
    this.lnkPIM = page.getByPlaceholder('Password');
    this.txtDashboard = page.getByRole('heading', { name: 'Dashboard' });
}
   

 

     async clickLinkLeave(){
           this.lnkLeave.click();
    }

    async clickLinkPIM(){
        this.lnkPIM.click();
    }

     async isDashboardTxtVisible(){
      await this.txtDashboard.waitFor({state: "visible"});  <<<< Here is the issue
       return this.txtDashboard.isVisible();
    }
}

LoginPage.ts

import { Locator, Page } from "@playwright/test";

export class LoginPage {

  readonly page: Page;
 
  readonly txtUsername: Locator;
  readonly txtPassword: Locator;
  readonly btnLogin: Locator;

  
  constructor(page: Page){
    this.page = page;
 
    this.txtUsername = page.getByPlaceholder('Username');
    this.txtPassword = page.getByPlaceholder('Password');;
    this.btnLogin = page.getByRole('button', { name: ' Login' });
}
   

 

     async login(username: string, password: string){
      await this.txtUsername.type(username);
      await this.txtPassword.type(password);
      await this.btnLogin.click();
     
    }

     async visit(){
      await this.page.goto("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");     
    }
}

App,.ts (This is kind of a wrapper class, where i don’t need to create objects from a page class inside tests every time)

import { Page } from "@playwright/test";
import { LoginPage } from "./LoginPage";
import { DashboardPage } from "./DashboardPage";

export class App {
    protected page: Page;
    
    constructor(page: Page){
        this.page = page;
    }

    public get LoginPage(): LoginPage{
        return new LoginPage(this.page);
    }

    public get DashboardPage(): DashboardPage{
        return new DashboardPage(this.page);
    }
}

What is the issue here? is it that the way Im using wait? How to fix this issue?

Using node/discord.js, how can I get my discord bot to parse an XML file and produce contents from within one of its tags as a response?

I’m trying to build a /lookup command that will read from a bunch of pre-prepared XML files and produce the contents as an embed response.

Ultimately, the syntax will be /lookup -> choose category -> choose name; e.g. /lookup ‘spell’ -> ‘acid splash’ -> bot delivers an embed with details parsed from the ‘spells’ XML file.

I’m having trouble getting the proof of concept together.

The XMLs all follow this same general structure (this is the contents of /xml/a.xml from my example below):

<spell>
        <name>Acid Splash</name>
        <level>0</level>
        <school>C</school>
        <ritual>NO</ritual>
        <time>1 action</time>
        <range>60 feet</range>
        <components>V, S</components>
        <duration>Instantaneous</duration>
        <classes>Fighter (Eldritch Knight), Rogue (Arcane Trickster), Sorcerer, Wizard, Artificer</classes>
        <text>You hurl a bubble of acid. Choose one creature you can see within range, or choose two creatures you can see within range that are within 5 feet of each other. A target must succeed on a Dexterity saving throw or take 1d6 acid damage.</text>
        <text>  This spells damage increases by 1d6 when you reach 5th Level (2d6), 11th level (3d6) and 17th level (4d6).</text>
        <text/>
        <text>Source: Player's Handbook p. 211</text>
        <roll>1d6</roll>
</spell>

This example has 2 different attempts (one is commented out), and both are arguably closer to my goal, but still not quite working as expected:

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
  .setName('test5')
  .setDescription('returns the contents of an xml file'),

  async execute(interaction){
    
    fs = require('fs');
    var parser = require('xml2json-light');

    fs.readFile( 'xml/a.xml', function(err, data) {

    // Attempt A
    // This version doesn't error, but it also doesn't produce a response...
    var xml = '<person><name>John Doe</name></person>';
    console.log("to json ->", xml);
    interaction.reply("to json ->", xml);
    
    // // Attempt B
    // // This version produces the attached error...
    // var json = parser.xml2json(data);
    // console.log("to json ->", data);
    // interaction.reply("to json ->", data);
    });
  }
}

The console log from Attempt A:

// NOTE: I CAN'T GET ANYTHING AFTER THE -> TO PRODUCE AS A RESPONSE FROM THE BOT BECAUSE IT'S REGARDED AS 'UNDEFINED'...

to json -> <person><name>John Doe</name></person>

The response my bot gives to Attempt A, however, as–according to err–it regards ‘data’ as ‘undefined’:

The response my bot gives to Attempt A

The error produced by Attempt B:

// NOTE: THERE MAY BE COMMENTED OUT LINES WHERE I ATTEMPTED TO TROUBLESHOOT THIS IN XML2JSON.JS...

*************************Smashmouth-2node_modulesxml2json-lightxml2json.js:67
    xmlStr = xmlStr.replace( /<!--[sS]*?-->/g, '' ); //remove commented lines
                    ^

TypeError: xmlStr.replace is not a function
    at cleanXML (C:UserssnakeOneDriveDocumentsdiscordSmashmouth-2node_modulesxml2json-lightxml2json.js:67:21)
    at Object.xml2json (C:UserssnakeOneDriveDocumentsdiscordSmashmouth-2node_modulesxml2json-lightxml2json.js:11:14)
    at C:UserssnakeOneDriveDocumentsdiscordSmashmouth-2commandsutilitytest5.js:23:23
    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)

The contents of /node_modules/xml2json-light/xml2json.js, which may have some commented out lines where I attempted to troubleshoot to no avail:

// NOTE: THERE MAY BE COMMENTED OUT LINES WHERE I ATTEMPTED TO TROUBLESHOOT THIS IN HERE...

'use strict';

module.exports = {
    xml2json: xml2json
};

//***********************************************************************
// Main function. Clears the given xml and then starts the recursion
//***********************************************************************
function xml2json(xmlStr){ 
    xmlStr = cleanXML(xmlStr);
    return xml2jsonRecurse(xmlStr,0); 
}

//***********************************************************************
// Recursive function that creates a JSON object with a given XML string.
//***********************************************************************
function xml2jsonRecurse(xmlStr) {
    var obj = {},
        tagName, indexClosingTag, inner_substring, tempVal, openingTag;

    // if(!xmlStr) return;
    while (xmlStr.match(/<[^/][^>]*>/)) {
        openingTag = xmlStr.match(/<[^/][^>]*>/)[0];
        tagName = openingTag.substring(1, openingTag.length - 1);
        indexClosingTag = xmlStr.indexOf(openingTag.replace('<', '</'));

        // account for case where additional information in the openning tag
        if (indexClosingTag == -1) {

            tagName = openingTag.match(/[^<][w+$]*/)[0];
            indexClosingTag = xmlStr.indexOf('</' + tagName);
            if (indexClosingTag == -1) {
                indexClosingTag = xmlStr.indexOf('<\/' + tagName);
            }
        }
        inner_substring = xmlStr.substring(openingTag.length, indexClosingTag);
        if (inner_substring.match(/<[^/][^>]*>/)) {
            tempVal = xml2json(inner_substring);
        }
        else {
            tempVal = inner_substring;
        }
        // account for array or obj //
        if (obj[tagName] === undefined) {
            obj[tagName] = tempVal;
        }
        else if (Array.isArray(obj[tagName])) {
            obj[tagName].push(tempVal);
        }
        else {
            obj[tagName] = [obj[tagName], tempVal];
        }

        xmlStr = xmlStr.substring(openingTag.length * 2 + 1 + inner_substring.length);
    }

    return obj;
}

//*****************************************************************
// Removes some characters that would break the recursive function.
//*****************************************************************
function cleanXML(xmlStr) {
    
    // if(!xmlStr) return;
    xmlStr = xmlStr.replace( /<!--[sS]*?-->/g, '' ); //remove commented lines
    xmlStr = xmlStr.replace(/n|t|r/g, ''); //replace special characters
    xmlStr = xmlStr.replace(/ {1,}<|t{1,}</g, '<'); //replace leading spaces and tabs
    xmlStr = xmlStr.replace(/> {1,}|>t{1,}/g, '>'); //replace trailing spaces and tabs
    xmlStr = xmlStr.replace(/<?[^>]*?>/g, ''); //delete docType tags

    xmlStr = replaceSelfClosingTags(xmlStr); //replace self closing tags
    xmlStr = replaceAloneValues(xmlStr); //replace the alone tags values
    xmlStr = replaceAttributes(xmlStr); //replace attributes

    return xmlStr;
}

//************************************************************************************************************
// Replaces all the self closing tags with attributes with another tag containing its attribute as a property.
// The function works if the tag contains multiple attributes. 
//
// Example : '<tagName attrName="attrValue" />' becomes 
//           '<tagName><attrName>attrValue</attrName></tagName>'
//************************************************************************************************************
function replaceSelfClosingTags(xmlStr) {

    // if(!xmlStr) return;
    var selfClosingTags = xmlStr.match(/<[^/][^>]*/>/g);

    if (selfClosingTags) {
        for (var i = 0; i < selfClosingTags.length; i++) {

            var oldTag = selfClosingTags[i];
            var tempTag = oldTag.substring(0, oldTag.length - 2);
            tempTag += ">";

            var tagName = oldTag.match(/[^<][w+$]*/)[0];
            var closingTag = "</" + tagName + ">";
            var newTag = "<" + tagName + ">";

            var attrs = tempTag.match(/(S+)=["']?((?:.(?!["']?s+(?:S+)=|[>"']))+.)["']?/g);

            if (attrs) {
                for(var j = 0; j < attrs.length; j++) {
                    var attr = attrs[j];
                    var attrName = attr.substring(0, attr.indexOf('='));
                    var attrValue = attr.substring(attr.indexOf('"') + 1, attr.lastIndexOf('"'));
                    
                    newTag += "<" + attrName + ">" + attrValue + "</" + attrName + ">";
                }
            }

            newTag += closingTag;

            xmlStr = xmlStr.replace(oldTag, newTag);
        }
    }

    return xmlStr;
}

//*************************************************************************************************
// Replaces all the tags with attributes and a value with a new tag.
// 
// Example : '<tagName attrName="attrValue">tagValue</tagName>' becomes 
//           '<tagName><attrName>attrValue</attrName><_@attribute>tagValue</_@attribute></tagName>'
//*************************************************************************************************
function replaceAloneValues(xmlStr) {

    // if(!xmlStr) return;
    var tagsWithAttributesAndValue = xmlStr.match(/<[^/][^>][^<]+s+.[^<]+[=][^<]+>{1}([^<]+)/g);
    
    if (tagsWithAttributesAndValue) {
        for(var i = 0; i < tagsWithAttributesAndValue.length; i++) {

            var oldTag = tagsWithAttributesAndValue[i];
            var oldTagName = oldTag.substring(0, oldTag.indexOf(">") + 1);
            var oldTagValue = oldTag.substring(oldTag.indexOf(">") + 1);
            
            var newTag = oldTagName + "<_@ttribute>" + oldTagValue + "</_@ttribute>";
            
            xmlStr = xmlStr.replace(oldTag, newTag);
        }    
    }
    
    return xmlStr;
}

//*****************************************************************************************************************
// Replaces all the tags with attributes with another tag containing its attribute as a property.
// The function works if the tag contains multiple attributes.
//
// Example : '<tagName attrName="attrValue"></tagName>' becomes '<tagName><attrName>attrValue</attrName></tagName>'
//*****************************************************************************************************************
function replaceAttributes(xmlStr) {

    // if(!xmlStr) return;
    var tagsWithAttributes = xmlStr.match(/<[^/][^>][^<]+s+.[^<]+[=][^<]+>/g);

    if (tagsWithAttributes) {
        for (var i = 0; i < tagsWithAttributes.length; i++) {
           
            var oldTag = tagsWithAttributes[i];
            var tagName = oldTag.match(/[^<][w+$]*/)[0];
            var newTag = "<" + tagName + ">";
            var attrs = oldTag.match(/(S+)=["']?((?:.(?!["']?s+(?:S+)=|[>"']))+.)["']?/g);

            if (attrs) {
                for(var j = 0; j < attrs.length; j++) {
                    
                    var attr = attrs[j];
                    var attrName = attr.substring(0, attr.indexOf('='));
                    var attrValue = attr.substring(attr.indexOf('"') + 1, attr.lastIndexOf('"'));
                    
                    newTag += "<" + attrName + ">" + attrValue + "</" + attrName + ">";
                }
            }

            xmlStr = xmlStr.replace(oldTag, newTag);
        }
    }

    return xmlStr;
}

Next.js 13: Can this components use server component and client component together for better performance? How to achieve it?

Introduce

I’m curently learning server and client components in Next.js 13 and wants to implement it in my project. I have a container component that uses react-intersection-observer to determine which section is in view and updates the active state for the navbar. I want to fetch data securely in the about component using the server component and load Home and Divisions components quickly using the server component, as those components don’t use any events or hooks.

Question

I’m confused about how to include the children components (About and Divisions) inside the corresponding sections in the ContainerClient component. I’ve unsure if it’s possible or if there are any tricks or alternative approaches to achieve this.

page.tsx

// In Server Component what i want: 
import ContainerClient from '@/components/landingPage/ContainerClient';
import Home from '@/components/landingPage/Home';
import About from '@/components/landingPage/About';
import Divisions from '@/components/landingPage/Divisions';

export default function Page() {
return (
     <ContainerClient>
          <Home />
          <About />
          <Divisions /> 
      </ContainerClient>
)}

ComponentClient.tsx

'use client';
import React, { useEffect, useState } from 'react';
import { useInView } from 'react-intersection-observer';
import Navbar from '../Navbar';
import NavbarMobile from '../NavbarMobile';

type Props = {
  children: React.ReactNode;
};

const ContainerClient: React.FC<Props> = ({ children }) => {
  const [active, setActive] = useState<string>('home');

  const [refHome, inViewHome] = useInView({
    threshold: 0.2,
  });
  const [refAbout, inViewAbout] = useInView({
    threshold: 0.2,
  });
  const [refDivisions, inViewDivisions] = useInView({
    threshold: 0.2,
  });

  useEffect(() => {
    if (inViewHome) {
      setActive('home');
    } else if (inViewAbout) {
      setActive('about');
    } else if (inViewDivisions) {
      setActive('divisions');
    }
  }, [inViewHome, inViewAbout, inViewDivisions]);
  return (
    <>
      <Navbar active={active} />
      <NavbarMobile active={active} />
      <main className="relative bg-primary overflow-x-hidden">
        {/* Home */}
        <section
          ref={refHome}
          className="relative max-w-[1800px] max-h-[1800px] 2xl:mx-auto w-full lg:h-[270vh] h-[200vh] bg-home-mobile lg:bg-home bg-primary bg-center bg-blend-screen bg-opacity-70 
            bg-[length:100vw_200vh] lg:bg-[length:110vw_270vh] over:bg-[length:1800px_1800px] flex flex-col"
          id="home"
        >
          {children}
        </section>
        {/* About */}
        <section  ref={refAbout}
      className="relative max-w-[1800px] max-h-[4000px] 2xl:mx-auto w-full h-max bg-about-mobile lg:bg-about bg-no-repeat bg-top bg-[length:170vw_150vh] lg:bg-[length:100vw_270vh] over:bg-[length:1800px_1800px] flex flex-col z-10">
        {/* I'm confused how to put About component children in here / it is imposible to do it / there are some tricks or way?*/}
        </section>
        {/* Divisions */}
        <section ref={refDivisions}>
          {/* I'm confused how to put Divisions component children in here / it is imposible to do it / there are some tricks or way?*/}
        </section>
      </main>
    </>
  );
};

I want to make the Home, About and Division components adopt a server component and still use react-intersection-observer to observe each section currently in view

How to resolve undefined error when variable is initialized with some value

Below is my code i want to use latitude and longitude returned by geolocation api in other function, i am getting undefined error
Error ->Uncaught TypeError: Cannot read properties of undefined (reading ‘coords’)
When i have done console.log(position) its showing that function has coords :-

GeolocationPosition {coords: GeolocationCoordinates, timestamp: 1689489347429}
coords: GeolocationCoordinates {latitude: 26.8500992, longitude: 80.9500672, altitude: null, accuracy: 6721.35220426669, altitudeAccuracy: null, …}
timestamp: 1689489347429
[[Prototype]]: GeolocationPosition

Below is my code:

  function positionSuccess(position){
   
  console.log(position)
    var lat = position.coords.latitude
   
   
   return function(){ 
    return lat
   }

  }

 
  const positionError =(error)=>{
    console.error(error)
  }
 navigator.geolocation.getCurrentPosition(positionSuccess,positionError);