Scroll Animation component does not work with Next.js but worked with create react app

I recently migrated a small project from create react app to next js.

All is fine besides that my code for scroll animations suddenly does not work in Next js and I am not sure why. A it does not throws errors, the animation just does not happen at all.
But it worked perfectly fine inside my create react app project.

I am not sure where the issue is. Has anyone a tip?

Thats the component.

 'use client';
import { useEffect, useRef, useState } from 'react';

export interface IProps {
  children: React.ReactNode;
  variant: 'slideFromRight' | 'slideFromLeft';
}

function useIsVisible(ref: React.RefObject<HTMLDivElement>) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      //remove if for more than one animation
      if (entry.isIntersecting) setVisible(entry.isIntersecting);
    });
    if (ref.current !== null && observer.takeRecords().length === 0)
      observer.observe(ref.current);
    return () => {
      observer.disconnect();
    };
  });

  return visible;
}

export default function ScrollAnimation(props: IProps) {
  //state handling
  const ref = useRef<HTMLDivElement>(null);
  const visible = useIsVisible(ref);

  return (
    <div ref={ref}>
      <div className={visible ? 'animate-' + props.variant : 'notVisible'}>
        {props.children}
      </div>
    </div>
  );
}

And then I import it and wrap it this way:

<ScrollAnimation variant="slideFromRight">
    <h1 className="text-white font-bold text-2xl ">Lorem Ipsum</h1>
        <hr className="border border-white my-4" />
        <p className="text-white font-montserrat text-left font-bold">
          Lorem Ipsum is simply dummy text of the printing and typesetting
          industry. Lorem Ipsum has been the industrys standard dummy text ever
          since the 1500s, when an unknown printer took a galley of type and
          scrambled it to make a type specimen book. It has survived not only
          five centuries, but also the leap into electronic typesetting,
          remaining essentially unchanged. It was popularised in the 1960s with
          the release of Letraset sheets containing Lorem Ipsum passages, and
          more recently with desktop publishing software like Aldus PageMaker
          including versions of Lorem Ipsum
        </p>
      </ScrollAnimation>

the slideFromLeft and Right is declared in my tailwind config:

keyframes: {
        slideFromLeft: {
          '0%': {
            transform: 'translate3d(-100%, 0, 0)',
            visibility: 'hidden',
          },
          '100%': {
            transform: 'translateZ(0)',
          },
        },
        slideFromRight: {
          '0%': {
            transform: 'translate3d(100%, 0, 0)',
            visibility: 'hidden',
          },
          '100%': {
            transform: 'translateZ(0)',
          },
        },
      },
       animation: {
        slideFromLeft: '3s both slideFromLeft ',
        slideFromRight: '3s both slideFromRight ',
      },

Here is a codesandbox with a minimal reproducible code example, but the animation never gets triggered, however the same code works in a create react app (CRA) setup without issues.

Codesanbox

ReactJS crashes when ran in docker

I’m trying to dockerize my react app.

But when I go to run it, it immediately stops. No errors.

Here is my docker-compose.yml file:

frontend:
    build:
      context: ../frontend
      dockerfile: Dockerfile.react
    ports:
      - "3000:3000"  # Map port 3000 on the host to 3000 in the container
    volumes:
      - ../frontend:/react-app
    environment:
      - REACT_APP_API_URL=http://localhost:3030
    depends_on:
      - apiserver
    networks:
      - mynetwork  # Connect this service to the custom network
networks:
  mynetwork:

And here is my Dockerfile:

FROM node:latest
WORKDIR /react-app

COPY package.json package.json
COPY public/ public
COPY src/ src

RUN npm install

EXPOSE 3000

CMD ["npm", "start"]

And finally, what shows up in the logs:

2023-09-23 02:51:14 
2023-09-23 02:51:14 > [email protected] start
2023-09-23 02:51:14 > react-scripts start
2023-09-23 02:51:14

I’m at a loss. I’ve tried everything and have been searching for hours.

Any help would be greatly appreciated

Everything. Searched SOF for hours

Events are not loading into the webix scheduler calendar

I want to show events in webix scheduler UNIT view But events are not getting displayed on calendar. My url is fine and receiving a successful response from the server with the data I need for the events. The response contains an array of events, and each event object has properties such as id, title, start, end, and url.

JSON response and code

var data = {
  "response": "success",
  "events": [
    {
      "id": 46,
      "url": "",
      "title": "Jeremy Madison",
      "start": "2023/09/28 09:45:00 AM",
      "end": "2023/09/28 09:45:00 AM",
      "extendedProps": {
        "calendar": "business",
        "model": {
          "id": 46,
          "appointment_type": "medical",
          "user_id": 1,
          "service_id": 1,
          "company_id": 1,
          "patient_id": 20,
          "location_id": 1,
          "time_id": null,
          "start": "2023-09-28 09:30:00",
          "end": "2023-09-28 09:45:00",
          "time": "9:30 AM",
          "duration": "15",
          "allDay": 0,
          "appointment_alert": null,
          "frequency": "1 day",
          "status": 0,
          "created_at": "2023-08-04 15:08:41",
          "updated_at": "2023-08-04 15:08:41",
          "policy_holder": null,
          "location": "peshawar",
          "code": "34214",
          "payer_name": null,
          "mobile_no": "+1 (907) 769-9091n",
          "dob": "2006-10-23",
          "admin_sex": "female",
          "clinician_name": "Sudais Khan",
          "patient_name": "Jeremy Madison"
        }
      }
    }
  ]
}
webix.ready(function () {
    webix.CustomScroll.init();
    var id = 5;
    var apiUrl = "schedules?nid=" + id;
    var eventsLoaded = false;
    var scheduler = webix.ui({
       view: "scheduler",
       container: "all_schedules",
       id: "myScheduler",
       width: 1000,
       height: 1000,
       save: "rest->" + apiUrl,
       url: apiUrl,
       monthSelect: true,
       weekHeader: true,
       events: new webix.DataCollection({
          scheme: {
             $init: function (obj) {
                obj.start_date = webix.Date.isDate(obj.start)
                   ? obj.start
                   : webix.Date.strToDate("%Y/%m/%d %H:%i")(obj.start);
                obj.end_date = webix.Date.isDate(obj.end)
                   ? obj.end
                   : webix.Date.strToDate("%Y/%m/%d %H:%i")(obj.end);
             },
          },
       }),
       on: {
          onBeforeEventSave: function (id, data, update) {
             if (update) {
                data.start = webix.Date.dateToStr("%Y/%m/%d %H:%i")(data.start_date);
                data.end = webix.Date.dateToStr("%Y/%m/%d %H:%i")(data.end_date);
             } else {
                data.start = webix.Date.dateToStr("%Y/%m/%d %H:%i")(data.start_date);
                data.end = webix.Date.dateToStr("%Y/%m/%d %H:%i")(data.end_date);
             }
          },
       },
    });
    scheduler.attachEvent("onViewChange", function (newView) {
       if (!eventsLoaded && newView === "month") {
          scheduler.clearAll(); 
          scheduler.load(apiUrl, "json");
          eventsLoaded = true;
       }
    });
 });

How to limit GooglePlacesAutocomplete search results?

I’m having a problem with the google places autocomplete API.

I defined a circle which includes the city of Paris and a few nearby towns.

Autocomplete shows me the addresses that are in the circle very well but I have a small problem, which is that some addresses that are not in the circle are also displayed.
For example in the city ‘BEZONS’ or ‘CRETEIL’ which I have framed in red some addresses are displayed in the autocomplete, while as you see, these cities are not in the circle.

How to solve this problem ?

Voici mon code :

const circle = new window.google.maps.Circle({
    center: new window.google.maps.LatLng(
        parseFloat(googleMapsData.latitude), // 48.86231356043533
        parseFloat(googleMapsData.longitude) // 2.3392018491517104
    ),
    radius: parseFloat(googleMapsData.radius) // 10000
});

const Restrc = {
    input: deliveryAddressPlacesValue,
    types: ['address'],
    locationRestriction: circle.getBounds(),
    strictBounds: true
}

SCREENSHOT

I have no idea where the problem is coming from, is it a problem in the google maps database?

Unauthorize user on 401 response (using contxt) in React Native

I had an old app which I’m refactoring and fixing. The flow required me to change AsyncStorage using to AuthProvider with context for the user entity. So I have useAuth hook, where is auth process and I keep user in the context. Also, I have WebService class which contains a lot of function for API:

async post(url, body, method = 'POST') {
    try {
        const response = await fetch(urlApi + url, {
            method: method,
            headers: await this.header(),
            body: JSON.stringify(body),
            redirect: 'follow'
        });

        const json = await response.json();

        if (response.status === 401) {
            await (new Storage).remove('user')
                .then((status) => {
                    if (status) {
                        reset({
                            index: 0,
                            routes: [{name: 'Login'}]
                        });
                    }
                });
        }

        return json;

    } catch (error) {
        console.log('WS POST', error);
    }
}
...
async editMessage(id, message) {
    return await this.post('bulletin-messages/' + id, { message }, 'PUT');
}
...

Previously, user was in Storage, but now it is in context. All I need to change inside if (response.status === 401) { ... } something like setUser(null) but I can’t use my useAuth hook (with updateUser() function), because WebService is not component. Handle interceptors after every usage of my function in components will be weird, so what should I do?

I was thinking about changing WebService to hook, but just realized that using hooks inside hooks is also wrong.

One more solution that might work is redux, but it is still not sure if will it work and, honestly, would prefer to leave the context

JavaScript exception handling not working

The following JavaScript exception handling is not working for maplibre library code. It always throws Invalid feature ID error.

enter image description here

try{
  var features = apex.region( "map-region" ).getFeature(layer, featureId);
} catch(err) {
  console.log(err.message)
};

NextJs `getServerSideProps` is never executed

I know that getServerSideProps can only be implemented in pages and not in components. And here I already implemented it in the src/app/posts/[id]/page.tsx file, but never executed though.

src/app/posts/[id]/page.tsx file:

import MainLayout from "@kocheng/components/layout/MainLayout";
import SinglePost from "@kocheng/components/SinglePost";
import { FC } from "react";
import { Post } from "@kocheng/dummy-data/Post";
import { GetServerSidePropsContext, PreviewData } from "next";
import { httpAPI } from "@kocheng/lib/axios";
import { ParsedUrlQuery } from "querystring";

type SinglePostPageProps = {
  params: { id: string };
  searchParams?: { [key: string]: string | string[] | undefined };
  post?: Post;
}

const SinglePostPage: FC<SinglePostPageProps> = ({
  params,
  searchParams,
  post,
}) => {
  console.log({ post }) // always undefined
  
  return (
    <MainLayout>
      <div className="container py-4 px-32 flex flex-col items-center">
        {!post ? (
          <h1 className="text-5xl">404 - NOT FOUND</h1>
        ) : (
          <SinglePost post={post}/>
        )}
      </div>
    </MainLayout>
  );
};

export async function getServerSideProps (
  context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>
) {
  const id = parseInt(context.params?.id as string) || 1;
  console.log("Fetching data") // never printed in the server console/terminal
  const post = await httpAPI.get(`/posts/${id}`).then(({ data: res }) => {
    const { data }: { data: Post } = res;
    return data
  });
  console.log("Data Fetched") // never printed in the server console/terminal
  console.log({ post })
  
  return { props: { post } }
}


export default SinglePostPage;

Did I do something wrong? Or is there any other successful alternatives? Thanks

check in js if actual text or whitespace of an element was clicked

I would like to know if it is possible to differ between the text and the white space of an element if clicked.

Example:

I have unsuccessful tried following:

body.addEventListener('contextmenu', (e) => {
    e.preventDefault(); // Prevent the default context menu
    const clickX = e.clientX;
    const clickY = e.clientY;
    item = e.target; // Get the clicked element
    if (item.textContent.trim() !== '') { do sth...; }
});

Cannot set properties of undefined (setting ‘onclick’)

Getting error that onclick is applied on undefined, although i am passing the node element.

html

<div class="gallery">
          <img src="image1.png" id="prdImg" />
          <div class="control">
            <span class="btn active"></span>
            <span class="btn"></span>
            <span class="btn"></span>
          </div>
        </div>

JS

const prdImg = document.getElementById("prdImg");
const btn = document.getElementsByClassName("btn");

for (let i = 0; i <= btn.length; i++) {
  btn[i].onclick = function () {
    prdImg.src = `image${i + 1}.png`;
    for (bt of btn) {
      bt.classList.remove("active");
    }
    this.classList.add("active");
  };
}

Issues connecting React hook form validated with zod, with Email Js

I am having issues connecting Email js with my React Hook Form, there are various issues like it wont submit on click and can’t figure out a way to use ref attribute with the <form> tag, as it’s mentioned in the official documentation.

Here’s my code

'use client'

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import Image from "next/image";
import { useState } from "react";
import emailjs from '@emailjs/browser';

import contact from "@/assets/images/contact.png";


const UserValidation = z.object({
    name: z.string().min(3).max(50),
    email: z.string().email(),
    message: z.string().min(10).max(500),
});

interface Props {
    user: {
        name: string;
        email: string;
        message: string;
    };
}

const Contact = () => {
    const form = useForm({
        resolver: zodResolver(UserValidation),
    });

    const onSubmit = () => (data: z.infer<typeof UserValidation>) => {

        emailjs.sendForm('__service_key', '__template__', JSON.stringify(data), '__API__')
            .then((result) => {
                console.log(result.text);
            }, (error) => {
                console.log(error.text);
            });

        form.reset();
    }

    return (


        <div className="my-20">
            <div className="my-12">

                <h1 className="text-3xl md:text-5xl text-center font-serif font-bold">
                    Contact <span className="text-primary">Us</span>
                </h1>

                <h1 className="text-base text-center font-sans font-thin mt-4">
                    We would love to hear from you
                </h1>

            </div>

            <div className="md:grid md:grid-cols-2 mb-12">


                <div className="m-12 md:m-0 md:ml-36 ">



                    <Form {...form} >
                        <form onSubmit={form.handleSubmit(onSubmit)}>
                            <FormField control={form.control} name="name" render={({ field }) => (
                                <FormItem className='flex flex-col gap-1 w-full mt-4'>
                                    <FormLabel className='text-light-1 font-sans font-sm'>
                                        Name
                                    </FormLabel >
                                    <FormControl className='flex-1 text-base-semibold text-secondary'>
                                        <Input type='text' className='border-primary account-form_input no focus' {...field} />
                                    </FormControl>
                                </FormItem>)}
                            />
                            <FormField control={form.control} name="email" render={({ field }) => (
                                <FormItem className='flex flex-col gap-1 w-full mt-4'>
                                    <FormLabel className='text-light-1 font-sans font-sm'>
                                        Email
                                    </FormLabel >
                                    <FormControl className='flex-1 text-base-semibold text-secondary'>
                                        <Input type='email' className='border-primary account-form_input no focus' {...field} />
                                    </FormControl>
                                </FormItem>)}
                            />

                            <FormField
                                control={form.control}
                                name="message"
                                render={({ field }) => (
                                    <FormItem className='flex flex-col gap-1 mt-4 w-full'>
                                        <FormLabel className='text-light-1 font-sans font-sm'>
                                            Message
                                        </FormLabel>
                                        <FormControl className='flex-1 text-base-semibold text-secondary'>
                                            <Textarea rows={10} className='border-primary account-form_input no focus' {...field} />
                                        </FormControl>
                                    </FormItem>
                                )}
                            />

                            <div className="flex">
                                <Button type="submit" className='bg-primary mt-4 flex-1'>Submit</Button>
                            </div>

                        </form>
                    </Form>
                </div>

                <div className="m-12 md:m-0 md:ml-28">
                    <Image src={contact} alt="contact" className="rounded-lg shadow-custom" height={470} width={470} />
                </div>
            </div>
        </div>
    )

}

export default Contact;

The official documentation mentions it like:

import React, { useRef } from 'react';
import emailjs from '@emailjs/browser';

export const ContactUs = () => {
  const form = useRef();

  const sendEmail = (e) => {
    e.preventDefault();

    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY')
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
  };

  return (
    <form ref={form} onSubmit={sendEmail}>
      <label>Name</label>
      <input type="text" name="user_name" />
      <label>Email</label>
      <input type="email" name="user_email" />
      <label>Message</label>
      <textarea name="message" />
      <input type="submit" value="Send" />
    </form>
  );
};

you can also visit my github for the whole code: https://github.com/dipesh2508/health-optima

How to separate html search list and link back to original code?

I am a complete beginner to html, css, and js. I have been trying to learn from w3schools.com and came across the How TO – Filter/Search List (https://www.w3schools.com/howto/howto_js_filter_lists.asp). I would like to know how to place the list of names in the <ul id="myUL"> as a separate html file named data.html and how to link it back to the initial html so that it functions exactly the same but with a separated data.html? Below is the entire example code from the w3schools.com site. I appreciate all the guidance.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
</style>
</head>
<body>

<h2>My Phonebook</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>

  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>

  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

<script>
function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
</script>

</body>
</html>

I would like to know how to place the list of names in the <ul id="myUL"> as a separate html file named data.html and how to link it back to the initial html so that it functions exactly the same but with a separated data.html?

How can I forward a SignalWire call to a Relay application from a PHP LaML webhook, and handle it in a JavaScript-based Relay application?

I’m developing a PHP application that utilizes SignalWire for handling incoming calls. I’ve set up a LaML webhook in PHP, and when a call is received, it triggers the webhook successfully. Additionally, based on the webhook response, I’ve configured SignalWire to forward the call to a SIP.

My current setup works well up to this point.

Specifically, I’m looking for guidance on How can I create the XML file for forword call to a Relay topic?

If anyone has experience or can provide code examples, documentation references Please provide the details.
Thanks in advance for your assistance!