problem with updating data using js in django chat

Good afternoon
Here i have django application, where must be chat
It dont need to be without delay, because of that i did it using simple models and tryed to make html grab new data about messages using js
As i readed in internet, it must work, but i think i made error, if someone can help, i will be very gratefull

here is chat.html

{% extends 'women/base.html' %}

{% load static %}
{% block content %}
<h1>Chat</h1>

<ul>
    {% for message in messages %}
    <li>
        <strong>{{ message.author.username }}:</strong> {{ message.content }} - {{ message.timestamp }}
    </li>
    {% endfor %}
</ul>

<form method="post" action="{% url 'send_message' chat.id %}">
    {% csrf_token %}
    <label for="message">Message:</label><br>
    <textarea id="message" name="content" rows="4" cols="50"></textarea><br>
    <button type="submit">Send</button>
</form>
{% endblock %}

{% block javascript %}
<script src="{% static 'women/js/chat.js' %}"></script>
{% endblock %}

it trying to call js file in my static folder women(application name)/static/women/js/chat.js

$(document).ready(function(){
    // Extract chat_id from the URL
    var chat_id = window.location.pathname.split('/')[2];

    function fetchMessages(){
        $.ajax({
            url: '/chat/' + chat_id + '/',  // replace with your view's URL
            success: function(data){
                // assuming 'data' is a list of messages
                $('ul').empty();  // clear the current list
                data.forEach(function(message){
                    $('ul').append('<li><strong>' + message.fields.author + ':</strong> ' + message.fields.content + ' - ' + message.fields.timestamp + '</li>');
                });
            }
        });
    }
    fetchMessages();  // fetch messages immediately when the page loads
    setInterval(fetchMessages, 1000);  // then fetch messages every 20 seconds
});

this is view function for chat


def chat_view(request, chat_id):
    chat = Chat.objects.get(id=chat_id)
    messages = Message.objects.filter(chat=chat)

    # Check if the request is an AJAX request
    if request.is_ajax():
        # Serialize the messages to JSON and return a JsonResponse
        messages_json = serializers.serialize('json', messages)
        return JsonResponse(json.loads(messages_json), safe=False)

    context = {
        'chat': chat,
        'messages': messages
    }
    return render(request, 'women/chat.html', context)


def send_message(request, chat_id):
    if request.method == 'POST':
        chat = Chat.objects.get(id=chat_id)
        content = request.POST.get('content')  # Assuming 'content' is the name of your input field
        message = Message(chat=chat, author=request.user, content=content)
        message.save()
        return redirect('chat_view', chat_id=chat.id)  # Assuming 'chat_view' is the name of your chat view

and i think you maybe need to see urls for chatting

    path('initiate-chat/<int:post_id>/', initiate_chat, name='initiate_chat'),
    path('chat/<int:chat_id>/', chat_view, name='chat_view'),
    path('chat/<int:chat_id>/send/', send_message, name='send_message'),

It can save messages, but js file that must grab new messages without reloading page is not work

I tryied to fiend error, but i did not. I will be very gratefull to someone who can help me.

agora web sdk (video calling) remote user screen sharing status

I am working on agora web sdk (video calling) pure javascript. i integrated video calling and it is working. when remote users sharing screen , not getting any screen sharing status to update UI. I tried so many ways using user-published events but didn’t worked. in this event both video track and screen track sharing screen kind status is video only. i want to detect remote users screen sharing status. please anyone let me know. Here i am using pure javascript not npm.

need to know agora web sdk remote users screen sharing status

Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unrecognized token ‘<'

I am making this app on react and following the transformer.js tutorial from the hugging face library here: https://huggingface.co/docs/transformers.js/en/tutorials/react

I wrote the code myself first and got the error in the title and then copy and pasted everything from the source code and I still get this error. the error is coming from the worker.js file which is this code:

import { pipeline } from '@xenova/transformers';

/**
 * This class uses the Singleton pattern to ensure that only one instance of the
 * pipeline is loaded. This is because loading the pipeline is an expensive
 * operation and we don't want to do it every time we want to translate a sentence.
 */
class MyTranslationPipeline {
    static task = 'translation';
    static model = 'Xenova/nllb-200-distilled-600M';
    static instance = null;

    static async getInstance(progress_callback = null) {
        if (this.instance === null) {
            this.instance = pipeline(this.task, this.model, { progress_callback });
        }

        return this.instance;
    }
}

// Listen for messages from the main thread
self.addEventListener('message', async (event) => {
    // Retrieve the translation pipeline. When called for the first time,
    // this will load the pipeline and save it for future use.
    let translator = await MyTranslationPipeline.getInstance(progress => {
        console.log(progress);
        // If progress is not intended to be JSON, pass it directly
        self.postMessage(progress);
    });
    


    // Actually perform the translation
    let output = await translator(event.data.text, {
        tgt_lang: event.data.tgt_lang,
        src_lang: event.data.src_lang,

        // Allows for partial output
        callback_function: x => {
            self.postMessage({
                status: 'update',
                output: translator.tokenizer.decode(x[0].output_token_ids, { skip_special_tokens: true })
            });
        }
    });

    // Send the output back to the main thread
    self.postMessage({
        status: 'complete',
        output: output,
    });
});

And i think the line that is giving me the error is this code:

let translator = await MyTranslationPipeline.getInstance(progress => {
        console.log(progress);
        // If progress is not intended to be JSON, pass it directly
        self.postMessage(progress);
    });

If you guys need more information please ask. Thanks for the help!

Hi. Can I add a play button to Superset dashboards

In superset, have a table. Can I add a play button to Superset dashboards. When button clicked a sound should play like play button in JS.

Thanks.
Best Regards.

Hi. In superset, have a table. Can I add a play button to Superset dashboards. When button clicked a sound should play like play button in JS.

i can’t run the javacript project

i run this command “pnpm install” and then this error message appear

pnpm : File C:UsersUserAppDataRoamingnpmpnpm.ps1 cannot be loaded. The file
C:UsersUserAppDataRoamingnpmpnpm.ps1 is not digitally signed. You cannot run this script on the current system.
For more information about running scripts and setting execution policy, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1

  • pnpm install
  •   + CategoryInfo          : SecurityError: (:) [], PSSecurityException
      + FullyQualifiedErrorId : UnauthorizedAccess
    
    

i’m trying to open my website that run in node js environment

Random Errors in intellij

Argument type {} | {count: any} is not assignable to parameter type FormatMessageValues | undefined

{formatMessage('count',value === '-1' ? {} : { count: totalCount })}

I get these random errors in Intellij and all the lines with be red. I don’t get this error in vs code, the code point of view everything is fine but I get this error.

I am using IntelliJ IDEA 2022.2.5 (Ultimate Edition), Build #IU-222.4554.10, built on March 15, 2023

I updated intellij to latest still i see the error. is it due to eslint? I am using eslint": "~8.51.0

javascript memory, how much data is too much

I make a service in nodejs that will run once a day, the service will get all data in that day from a NoSQL database (around 200,000 objects) and do some aggregation and insert the aggregated data to NoSQL database (around 200 objects).

is handling 200,000 objects too much for javascript? how much memory estimation will the service take? what are the best practices?

Initiating CSS Animation Only After Complete Page Load

i need a solution with WordPress.
In my case, i want to CSS Animtations only effect after the page is 100% loaded.
An example:
text

My HTML

 <div class="svg-one">
    <svg xmlns="http://www.w3.org/2000/svg" width="467" height="195" viewBox="0 0 467 195" fill="none">
      <path
        d="M-5.68701 0.4375C-5.68701 0.4375 304.086 30.9591 314.874 120C323.963 194.797 466.079 194.745 466.079 194.745"
        stroke="#1A3D96" stroke-width="0.34" stroke-miterlimit="10" stroke-linecap="round" />
    </svg>
    <svg xmlns="http://www.w3.org/2000/svg" width="468" height="196" viewBox="0 0 468 196" fill="none">
      <path
        d="M-6.0835 1.08398C-6.0835 1.08398 294.147 28.6178 303.406 117.71C311.193 192.584 467.721 194.851 467.721 194.851"
        stroke="#1A3D96" stroke-width="0.34" stroke-miterlimit="10" stroke-linecap="round" />
    </svg>
  </div>

My CSS


@keyframes fade-in-left-to-right {
    to {
        opacity: 1;
        stroke-dashoffset: 0;
    }
}


.svg-one {
    position: absolute;
    display: flex;
    flex-direction: column;
    left: 0;
    top: 25%;
    width: 14%;
}

.svg-one svg {
    position: absolute;
    display: block;
    width: 23vw;
    height: auto;
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
    opacity: 0.5;
    animation: fade-in-left-to-right 2.5s linear forwards;
    animation-delay: 1.2s;
}


.svg-one svg:nth-child(1) {
    top: 0px;
}

.svg-one svg:last-child {
    top: 70px;
}

Thanks for reading, have a great day!

A function let’s animations run only after the website loaded

TypeError: Cannot destructure property ‘basename’ of ‘React2.useContext(…)’ as it is null

It has been a while since I’ve worked with React-Router and the first time with v6. My applications is using:

  • Vite
  • React
  • Material-UI

I’ve attempted the following:

  • Searched the web
  • reread the docs multiple times
  • followed the react-router tutorial and applied it to my application

I’ve been taking a step by step approach to the application where I test each change before I go onto the next. It appears my routing is correct as I tested it by typing in the routes as the URL. However, when I attempt to add Link, I’m getting the out of context error. I know I’m missing something simple but I’m just not seeing it. Here is the code with imports omitted for brevity.

index.jsx

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <ThemeProvider theme={theme}>
      {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
      <CssBaseline />
      <App />
    </ThemeProvider>
  </React.StrictMode>
)

app.jsx

const router = createBrowserRouter([
  {
    path: "/",
    element: "",
    errorElement: <ErrorPage />,
    children: [
      {
        path: "/about",
        element: <About />,
      },
      {
        path: "/products",
        element: <Products />,
      },
      {
        path: "/",
        element: <Home />,
      },
    ]
  },

]);

function App() {
  const [count, setCount] = useState(0)

  return (  
    <><HeaderBar />
    <RouterProvider router={router}>
      <div>
        <Outlet />
        </div>
      </div>
    </RouterProvider></>
  )
}

export default App

HeaderBar.jsx (only failing element is shown for brevity)

<Button
  key={page.text}
  onClick={handleCloseNavMenu}
  sx={{ my: 2, color: 'white', display: 'block' }}
  component={Link}
  to={page.target}
>
  {page.text}
</Button>

I have attempted to create the context by trying to wrap <BrowserRouter> around various components, but receive error messages about having 2 routers in my application.

Uncaught ReferenceError: SwaggerUIBundle is not defined nodejs netlify

I am trying to setup my netlify code integrated with nodejs. Without netlify my swagger was working fine but after the netlify integrations My swagger page is not loading and throwing this error.

Uncaught SyntaxError: Unexpected token ‘<‘ (at swagger-ui-bundle.js:3:1)
swagger-ui-standalone-preset.js:3 Uncaught SyntaxError: Unexpected token ‘<‘ (at swagger-ui-standalone-preset.js:3:1)
swagger-ui-init.js:200 Uncaught ReferenceError: SwaggerUIBundle is not defined
at window.onload (swagger-ui-init.js:200:7)

My netlify.toml is

[functions]
  external_node_modules = ["express"]
  node_bundler = "esbuild"
[[redirects]]
  force = true
  from = "/api/*"
  status = 200
  to = "/.netlify/functions/api/:splat"

and my api.ts is

// YOUR_BASE_DIRECTORY/netlify/functions/api.ts

import express, { Router } from "express";
import serverless from "serverless-http";
import uploadRoutes from '../../routes/uploadRoutes'
import fileRoutes from '../../routes/fileRoutes'
import userRoutes from '../../routes/userRoutes'
import authRoutes from '../../routes/auth'
import config from '../../config/config'
import swaggerUi from 'swagger-ui-express'
import swaggerJSDoc from 'swagger-jsdoc'
import upload from '../../multerConfig'
import bodyParser from 'body-parser'
import connectToDatabase from '../../config/db'
import cors from 'cors'
import SwaggerUIBundle from 'swagger-ui-dist/swagger-ui-bundle';
import SwaggerUIStandalonePreset from 'swagger-ui-dist/swagger-ui-standalone-preset';



const swaggerSpec = swaggerJSDoc({
    encoding: 'utf8',
    failOnErrors: false,
    verbose: false,
    format: 'yaml', // or 'json', depending on your preference
    swaggerDefinition: config.swaggerDefinition,
    definition: {}, // or provide your Swagger definition here if needed
    apis: config.apiPaths,
});

const app = express();

app.use(cors());
// Handle preflight requests for all routes
app.options('*', cors()); 
// Serve Swagger UI
app.use('/api/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
const router = Router();

// Enable CORS


router.get('/hello', (req, res) => res.send('Hello World test v1!'));

app.use("/api", router);





// Middleware to set Access-Control-Allow-Origin header for all routes
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    next();
  });
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb' }));


// Parse JSON bodies
app.use(bodyParser.json());
// Parse URL-encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
// Use the upload routes
app.use(uploadRoutes);

// Use the file routes
app.use('/api', fileRoutes);
app.use(upload.single('file'));
app.use('/api', userRoutes);
app.use('/api/auth', authRoutes); // Fixed missing '/' at the beginning

// MongoDB URI
const mongoURI = config.mongoURI;

// Call the function to establish MongoDB connection
connectToDatabase(mongoURI);

export const handler = serverless(app);

Can anyone please guide me what I am doing wrong , I tried one solution of changing the order of swagger before route but there is no luck on that.

Can LocalStorage and SessionStorage be used inside a TypeScript decorator?

I am building a web page with HTML, CSS, and TypeScript. I had a Figma template to follow, and there were many parts of it that were boilerplate. To make future work easier, my plan was to register an HTML template for each class involved in the Figma design on localStorage using decorators. This way, I could dynamically build any structural pattern on the page. For example, if I have a product card in the Figma design, I then create a Product class below

import { h1, image, p } from "../cardAnotations/CardContentAnnotations.js";

export class Product {

    @h1
    private _name: string;
    @p
    private _description: string;
    @p
    private _price: number;

    @image
    private _imageSource:string;

    private _discountedPrice: number;

    private _imageDescription:string;

    constructor(name: string, description: string, price: number,imageSource:string
        , discountPercent: number) {

        
        this._name = name;
        this._description = description;
        this._price = price;
        this._imageSource = imageSource;
        this._imageDescription = ''
        this._discountedPrice = this.calculateDiscountedPrice(discountPercent);
    }

//Getters and Setters
.
.
.

Those decorators in the properties correspond to the respective HTML tag representations in the card.

<li>
    <img src="/src/assets/images/product01.png" alt=""> \ @image private _imageSource:string;

    <h1>peanut butter</h1>   \@h1 private _name: string;

    <p>the best peanut butter in america with extra protein</p> \@p private _description: string;

    <p>6.48<span class="greenText">6.22</span></p> \ @p private _price: number;
</li>

I tried using a singleton pattern to store the data initially, but it didn’t work inside a decorator. However, I still wanted a single instance to receive this data, so I created a type object to store the HTML data for each necessary class and then put it in the LocalStorage.

export type ObjectHTMLTemplate = {

    [prop: string]: string | imageTemplateObj;
  };

  export type TamplateObserver = {
    [prop:string]:ObjectHTMLTemplate
  }
 export type imageTemplateObj = {
    src:string;
    alt:string;
  }

the TamplateObserver final should look like this

{
    "Blog": {
        "_description": "p",
        "_date": "p",
        "_commentsNumber": "p",
        "_title": "h1"
    },
    "Product": {
        "_description": "p",
        "_price": "p",
        "_imageSource": "img",
        "_name": "h1"
    },
    "SectionCard": {
        "_shortMensage": "p",
        "_sectionName": "p",
        "_imageSource": "img"
    }
}

i put the pieces together like this

import { ObjectHTMLTemplate, TamplateObserver } from "../types/types.js";



export function image(target: any, key: string){


    let className:string = target.constructor.name;
    const tamplete = getFromLocalStorage("ClassesTamplate")
    
    if(tamplete){


        if (!tamplete[className]) {
            tamplete[className] = {} as ObjectHTMLTemplate;
        }

        tamplete[className][key] = 'img'

        
        saveToLocalStorage("ClassesTamplate",tamplete)
        

    }
    


    
}

export function h1(target: any, key: string){


    let className:string = target.constructor.name;

    const tamplete = getFromLocalStorage("ClassesTamplate")
    
    if(tamplete){



        if (!tamplete[className]) {
            tamplete[className] = {} as ObjectHTMLTemplate;
        }

        tamplete[className][key] = 'h1'

        
        saveToLocalStorage("ClassesTamplate",tamplete)
        

    }
}

export function p(target: any, key: string){



    let className:string = target.constructor.name;

    const tamplete = getFromLocalStorage("ClassesTamplate")
    
    if(tamplete){

        console.log(tamplete)        

        if (!tamplete[className]) {
            tamplete[className] = {} as ObjectHTMLTemplate;
        }

        tamplete[className][key] = 'p'
        saveToLocalStorage("ClassesTamplate",tamplete)

    }

}

export function h2(target: any, key: string){

    let className:string = target.constructor.name;
    const tamplete = getFromLocalStorage("ClassesTamplate")
    
    if(tamplete){



        if (!tamplete[className]) {
            tamplete[className] = {} as ObjectHTMLTemplate;
        }

        tamplete[className][key] = 'h2'

        
        saveToLocalStorage("ClassesTamplate",tamplete)
        

    }
}

async function saveToLocalStorage(key: string, value: TamplateObserver) {
    try {
        // Convert the object to a JSON string
        const jsonString = JSON.stringify(value);

        // Save to localStorage
        localStorage.setItem(key,jsonString);
        

        //console.log(`Object saved to localStorage with key: ${key}`);
    } catch (error) {
        console.error("Error saving object to localStorage:", error);
    }
}


 function getFromLocalStorage(key: string): TamplateObserver | null {
    try {
        const jsonString = localStorage.getItem(key);
        if (jsonString) {
            // Parse the JSON string to an object
            return JSON.parse(jsonString) as TamplateObserver;
        }
    } catch (error) {
        console.error("Error retrieving object from localStorage:", error);
    }

    return null;
}







export default class ObjectTemplateRepo {

    private  ObjectsTemplates:ObjectHTMLTemplate[];
    private _observe!:TamplateObserver;
    private static _instance:ObjectTemplateRepo;

    private constructor() {
        this.ObjectsTemplates = []
    }
    
    static getInstance():ObjectTemplateRepo{
        if (!ObjectTemplateRepo._instance) {

            ObjectTemplateRepo._instance = new ObjectTemplateRepo();

        }

        return ObjectTemplateRepo._instance;
    }

    public getObjectTemplate(key:string):ObjectHTMLTemplate | void{

        const template = getFromLocalStorage("ClassesTamplate");
    
        if (template && template[key]) {
            return template[key];
        }
    

    }

  



}









i used it to build a list of products like this

import ObjectTemplateRepo from "../cardAnotations/CardContentAnnotations.js";
import { Product } from "../models/Product.js";
import { SectionCard } from "../models/SectionCard.js";
import { ObjectHTMLTemplate, productTypeSectionAmount } from "../types/types.js";


export class ProductListInjection{

    constructor(){

    }

    injectList(targetListId: string, products?: Product[]): void {

        const htmlElementList = document.getElementById(targetListId) as HTMLElement;
        
        if (!htmlElementList) {
            throw new Error("tag no found");
        } 

        

        if (Array.isArray(products)){

            products.forEach((product =>{

                htmlElementList.appendChild(this.ProductPatternTamplete(product))

            }))

        }
    }

    ProductPatternTamplete(product:Product):HTMLLIElement{


        const objectsTemplate = ObjectTemplateRepo.getInstance();
        const tamplete = objectsTemplate.getObjectTemplate('Product') as ObjectHTMLTemplate;
        const divElement = document.createElement('li');

        const imageElement = document.createElement(tamplete._imageSource as string) as HTMLImageElement;
        const nameElement = document.createElement(tamplete._name as string);

    

        const descriptionElement= document.createElement(tamplete._description as string)
        const priceElement = document.createElement(tamplete._description as string)

        const discoutPriceElement = document.createElement('span');

        discoutPriceElement.className ="greenText";
        discoutPriceElement.innerHTML = "   " + product.discountedPrice.toString();
        

    

        imageElement.src = product.imageSource;
        imageElement.alt = product.imageDescription;
        nameElement.innerText = product.name
        descriptionElement.innerText = product.description
        priceElement.innerText = product.price.toString();
        priceElement.appendChild(discoutPriceElement);
        divElement.appendChild(imageElement);
        divElement.appendChild(nameElement);
        divElement.appendChild(descriptionElement);
        divElement.appendChild(priceElement);

        return divElement;

    }
}

Then, my problem is if I deploy it on GitHub Pages, it’s kind of like the decorator is not even called, but it works fine on my localhost. In this question, it suggests changing the localStorage to sessionStorage, but nothing changes on GitHub Pages, and on my localhost, the decorator is not called as in LocalStorage in the gitHub pages.

I tried to write a GitHub Action to build it on the GitHub machine, but it also did not work. Where can I find content about how decorators work internally and the real reason for this behavior with local and sessionStorage? I would like to understand more deeply how they work. There is no way to save local data with decorators ?

Can I selectively stop a ::part pseudo selector from overriding shadow dom css

I have exposed part of my shadow DOM via the PART pseudo element. The caller of my Custom Element takes advantage of that by using CSS like: –

#disTick::part(endo) {
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1); 
    background: linear-gradient(to top, #165273 0%, #33a1de 100%);
}   

The problem I have is that ENDO is a SPAN inside a LABEL that also contains a CHECKBOX. That problem being that ENDO is incapable of having Focus but a: –

input:hover + .endo.tick,
input:focus + .endo.tick {
  box-shadow: 0 0 0.5em var(--toggle-highlight-color, rgba(0,0,0,0)); 
}

in the shadow DOM is ignored as the BOX-SHADOW attribute from the light DOM overrules it even though it does not have a FOCUS pseudo element itself.

  • All code (3 files toggle) can be found here and a working example can be found here. (It’s the “Disable Toggle checkbox that can’t stay highlighted when focused.)

Ok, I realize I’m trying to have my cake and eat it too, or get half-pregnant, here but I hope you can see some logic in it?

I don’t want to add another PART to an already leaky shadow DOM so I guess I can have more CSS variables with really big strings for BOX-SHADOW. Just wondering if there is some CSS specificity or precedence lever that can force the Shadow DOM part:focus to overrule light DOM part?

Font customization using cms

Is there anyway of customizing fonts within the cms of the website.

My clients want to have a user friendly website, they requested that if they can have the ability to change the font of the website anytime they want.

I’ve tried looking for it in yt. But nothing appears to help

Why is my button not working at all when I click it?

I am making a to-do list with JS , React and HTML. The button in the HTML code:
<input type="button" value="Add your new task" id="newTaskBtn">
gets added with an event listener:
document.getElementById('newTaskBtn').addEventListener("click",addTask);
which calls the function addTask():

function addTask(){
        if (document.getElementById('newTask').value = " ") {
            alert('You have to write something.')
        } else {
            const root = ReactDOM.createRoot(document.getElementById('to-dos container'));
            root.render(<newTaskComponent content={document.getElementById('newTask').value}/>)
            {() => setId(c = c + 1);}
        }
    }

which checks if the input box:
<input type="text" name="addNewTask" id="newTask" value=" " placeholder="Add a new task">
is empty , if not , it calls the newTaskComponent component:

function newTaskComponent(props){
        return (
          <>
            <toDoId />
            <p>{props.content}</p>
            <Checkbox />
            <DeleteBtn />
          </>
        );
    }

which adds a checkbox, a delete button and gives the todo an id(Todo 1,Todo 2 …)
The toDoId() component:

function toDoId(){
        const [todos, setTodos] = useState([]);
        const addTodo = () => {
            setTodos((c) => [...c]);
          };

        return(
            <>
              <h1>{addTodo}</h1>
            </>
        )
    }

uses the setId() function declared at the addTask() function to give the todo an Id. Then the checkbox function:

function Checkbox(){
        if (document.getElementById('checkbox').checked) {
            alert('Congratulations!')
        } 
        return (
            <>
            <input type='checkbox' name='checkbox' id='checkbox'></input>
            <label for='checkbox'>Completed!</label>
              </>  
        )
    }

which congratulates you after the task is done(when checkbox checked).For the delete button:

 function DeleteBtn() {
        return(
            <>
            <button onClick={newTaskComponent = " " && alert(Deleted)}>Delete</button>
            </>
        )
    }

it deletes the newTaskComponent(base component) and alerts that the task is deleted.

I thought there was going to be to-dos after pressing the button, but it does not appear, the worst part is even the if statement which checks for blank input also does not work, it is simply like as if I did not write any code into the JS file, all source code is below and I hope a expert could give some help(also if able to explain in detail that would be better)

toDoList.html

<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="toDoList.js"></script>
    </head>
    <body>
        <div id="container">
            <div id="to do list">
                <form>
                    <h1>To-Do List:</h1>
<input type="text" name="addNewTask" id="newTask" value=" " placeholder="Add a new task">
                    <div id="to-dos container">
                        
                    </div>
                    <input type="button" value="Add your new task" id="newTaskBtn">
                </form>
            </div>
        </div>
    </body>
</html>

toDoList.js

import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function myFunction(){
    document.getElementsByTagName('body').addEventListener("load",myFunction);
    document.getElementById('newTaskBtn').addEventListener("click",addTask);

    function DeleteBtn() {
        return(
            <>
            <button onClick={newTaskComponent = " " && alert(Deleted)}>Delete</button>
            </>
        )
    }

    function Checkbox(){
        if (document.getElementById('checkbox').checked) {
            alert('Congratulations!')
        } 
        return (
            <>
            <input type='checkbox' name='checkbox' id='checkbox'></input>
            <label for='checkbox'>Completed!</label>
              </>  
        )
    }

    function toDoId(){
        const [todos, setTodos] = useState([]);
        const addTodo = () => {
            setTodos((c) => [...c]);
          };

        return(
            <>
              <h1>{addTodo}</h1>
            </>
        )
    }

    function newTaskComponent(props){
        return (
          <>
            <toDoId />
            <p>{props.content}</p>
            <Checkbox />
            <DeleteBtn />
          </>
        );
    }

    function addTask(){
        if (document.getElementById('newTask').value = " ") {
            alert('You have to write something.')
        } else {
            const root = ReactDOM.createRoot(document.getElementById('to-dos container'));
            root.render(<newTaskComponent content={document.getElementById('newTask').value}/>)
            {() => setId(c = c + 1);}
        }
    }

}

Please help and if the question is out of stackoverflow rules ,please do not delete the question, thank you.