How to pass a React component to a component and use it inside the component as a component?

I have a Button component that allows some props like variant, active, size etc. to change its styling.

What I want is, passing the Button component to another component and use it there as a normal component.

function Header() {
  return (
    <div>
      <Button.Link href="/">Log in</Button.Link>
      <Button.Link href="/">Sign up</Button.Link>
      <Dropdown
        Trigger={ 
          <Button variant="outline" size="icon">
            <MenuIcon className="size-4" />
          </Button>
        }
      >
        <div className="absolute right-0 top-8 h-72 w-64 bg-red-200">Hello</div>
      </Dropdown>
    </div>
  );
}

export default Header;

As you can see I am passing the Button component to the Dropdown component.

Now in Dropdown, I want to use it as shown below: (dummy code for explanation)

interface DropdownProps {
  Trigger: any;
  children: React.ReactNode;
}

function Dropdown({ Trigger, children }: DropdownProps) {
  const [isOpen, setIsOpen] = useState(false);

  const dropdownRef = useRef<HTMLDivElement>(null);

  const toggleDropdown = () => {
    setIsOpen((current) => !current);
  };

  useClickOutside(dropdownRef, () => setIsOpen(false));

  return (
    <div ref={dropdownRef} className="relative">
      {<Trigger onClick={toggleDropdown} active={isOpen} />} <-- like this
      {isOpen && children}
    </div>
  );
}

export default Dropdown;

How can I achieve this functionality?


What I have done:

I found a solution using React’s cloneElement but not happy with it (feels like there is a better way).

interface DropdownProps {
  trigger: React.ReactElement<{
    onClick: () => void;
    active: boolean;
  }>;
  children: React.ReactNode;
}

function Dropdown({ trigger, children }: DropdownProps) {
  const [isOpen, setIsOpen] = useState(false);

  const dropdownRef = useRef<HTMLDivElement>(null);

  const toggleDropdown = () => {
    setIsOpen((current) => !current);
  };

  useClickOutside(dropdownRef, () => setIsOpen(false));

  return (
    <div ref={dropdownRef} className="relative">
      {cloneElement(trigger, { onClick: toggleDropdown, active: isOpen })}
      {isOpen && children}
    </div>
  );
}

export default Dropdown;

Anything better?

Properties for automatic formal verification of the JavaScript code [closed]

I need a piece of advice from JavaScript guru.

I am developing a formal verification tool for a JavaScript developers (actually for the toy language which is a simplified version of JavaScript, no eval() function included, but still almost whole ECMA Standard).

I need to write a global predicate (or a library of predicates) which will contain some specifications and restrictions for functions from ECMA (hints for a developer).

So developer clicks “show me the hints” and his whole-program code would be automatically checked (via symbolic testing with SMT-solver at the core) for the situations when NaN or undefined behavior can happen… or when function can do something unexpected. It should be more than compiler can suggest, it should be some kind of formal verification.

I am going to write specifications for a JavaScript functions. Specifications, describing expected behavior.

What kind of specifications it can be? What unexpected behavior you faced in your JavaScript code?

Basically I need to inform developer that specific function he is using in his code can lead to undefined behavior in certain circumstances.

Example:
Programmer click “show hints” on next code

const foo = 42; // foo is a number
const result = foo + "1"; // 

My instrument will give him a hint:

Warning: foo will be coerced to the **string**! JavaScript coerces foo to a string, so it can be concatenated with the other operand.


Thank you

Properties for formal verification of the JavaScript code

I need a piece of advice from JavaScript guru.

I am developing a formal verification tool for a JavaScript developers (actually for the toy language which is a simplified version of JavaScript, no eval() function included, but still almost whole ECMA Standard).

I need to write a global predicate (or a library of predicates) which will contain some specifications and restrictions for functions from ECMA (hints for a developer).

So developer clicks “show me the hints” and his whole-program code would be automatically checked (via symbolic testing with SMT-solver at the core) for the situations when NaN or undefined behavior can happen… or when function can do something unexpected. It should be more than compiler can suggest, it should be some kind of formal verification.

I am going to write specifications for a functions from the standard library. Specifications, describing expected behavior.

What kind of specifications it can be? What functions from the standard library can you think of to add such specifications to them?

Basically I need to inform developer that specific function he is using in his code can lead to undefined behavior in certain circumstances.

Thank you

Promise redefinition does not affect promises returned by native functions

(See also this answer.)

When I redefine the Promise class (with a “monkey-patch” as shown below), this does not affect promises that are returned by a native function like fetch:

Promise = class extends Promise {
  constructor(executor) {
    console.log("Promise created");
    super(executor);
  }
}
console.log("Non-native promise");
Promise.resolve(1);
console.log("Native promise");
fetch("https://httpbin.org/delay/1");
console.log("Native promise");
document.hasStorageAccess();

When I run this snippet in the browser, the promise created by Promise.resolve uses the redefinition (so that “Promise created” is logged), but the promises returned by fetch or document.hasStorageAccess do not.

(When I try it in Node.js, fetch uses the redefinition, so it really depends on the implementation.)

I there a way to redefine Promise such that the redefinition is also used by native browser functions?

Javascript Fetch method gives me 404 Error, but async/await works fine. Also works fine when using breakpoints. What is going on?

I’m just learning about this topic and I was trying this code:

let srcTxt;
let src = fetch("https://dog.ceo/api/breeds/image/random")
    .then(response => response.json())
    .then(data => {
        srcTxt = data.message;
        data.message
    })
    .catch(error => console.log(error));

But I get Error 404: not found.

I tryied to debug on console and, when hitting a breakpoint after my fetch request and then resuming, the code works fine.

I changed to async – await syntax instead and it works perfectly fine as well.

Can anyone help me to understand what is happening?

I’m using a live server from WebStorm.

How to overwrite a configured permission settings

Unable to edit current permissions on set edit feature pack

I haven’t tried much. New to the android space within settings.

,,.,..,,…………….,…………………………………………………………………………………………………………………………………………………………………………………………………………………..

Unable to edit current permissions on set edit feature pack

I haven’t tried much. New to the android space within settings.

Unable to edit current permissions on set edit feature pack

I haven’t tried much. New to the android space within settings.

I don’t know how to execute the task as I do not have a PC to perform any abd functions

Open new tab in background with javascript angular

iam trying to open in new tab in background with angular, already browsing about this but it seems still doesn’t works.

please see the function below :

 openProductInNewTab(productId: number) {
    const url = this.router.serializeUrl(this.router.createUrlTree(['/product', 'detail', productId]));
    
    // Buka tab baru
    const newWindow = window.open(url, '_blank', 'noopener,noreferrer');
    
    setTimeout(() => {

    if (newWindow) {
      window.focus(); // Kembali ke tab utama
      }
    }, 500);
  }

here i attached the html code :

<td style="width: 27%; padding-left: 20px" nowrap *ngIf="this.ls.selectedLanguages == 'id'">
<strong (click)="openProductInNewTab(item.id)" class="text-blue">
              {{ item.name }}
            </strong>
          </td>

so the problem is, my browser (edge) is always open the new tab directly and never go back to the main tab. I want to stay focus on main tab and just open the new tab in background tab for the ideal solution. Do you have any alternative solution about this ? Thank you because iam getting stuck.

i have already trying iframe, put the url on variable a, add the windows.blur() but none of these ever work on my local instead.

In joy-con-webhid, why the ‘alpha’ orientation parameter is decreasing over time?

Joy-Con WebHID is a Javascript driver for Nintendo Joy-Cons with support for all buttons, analog sticks, and the device’s gyroscope and accelerometer sensors.

As you can see in the demo the orientation for ‘beta’ and ‘gamma’ stays in place, but for ‘alpha’ is always decreasing until it reaches zero.

How to prevent that?

  if (joyCon instanceof JoyConLeft) {
    rootStyle.setProperty('--left-alpha', `${orientation.alpha}deg`);
    rootStyle.setProperty('--left-beta', `${orientation.beta}deg`);
    rootStyle.setProperty('--left-gamma', `${orientation.gamma}deg`);
  } else if (joyCon instanceof JoyConRight) {
    rootStyle.setProperty('--right-alpha', `${orientation.alpha}deg`);
    rootStyle.setProperty('--right-beta', `${orientation.beta}deg`);
    rootStyle.setProperty('--right-gamma', `${orientation.gamma}deg`);
  }

Full source code here.

I would like to control a sword for a Javacript game using this driver.
How to correctly achieve that?

Sliding working not properly. I want it from the left. It comes from the right

This is my start.html:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Pepper App</title>
   
   {% load static %}
   <link rel="stylesheet" href="{% static 'css/start.css' %}">
</head>
<body>
   <div class="container">
      <!-- LOGIN Form -->
      <div class="form login-form active" id="loginForm">
         <div class="login-left"></div> <!-- Left section with background -->
         <div class="login-right form-content">
            <h2 class="form-title">Login</h2>
            <form>
               <div class="form-group">
                  <label for="username">Username or Email</label>
                  <input type="text" id="loginUsername" name="username" placeholder="Enter your username or email" required>
               </div>
               <div class="form-group">
                  <label for="password">Password</label>
                  <input type="password" id="password" name="password" placeholder="Enter your password" required>
               </div>
               <button type="submit">Login</button>
            </form>
            <p>Don't have an account? <span onclick="toggleForms()" class="toggle-text">Register</span></p>
         </div>
      </div>

      <!-- SIGNUP Form -->
      <div class="form signup-form" id="signupForm">
         <div class="signup-left form-content">
            <h2 class="form-title">Sign Up</h2>
            <form>
               <div class="form-group">
                  <label for="username">Username</label>
                  <input type="text" id="signupUsername" name="username" placeholder="Enter your username" required>
               </div>
               <div class="form-group">
                  <label for="email">Email</label>
                  <input type="email" id="email" name="email" placeholder="Enter your email" required>
               </div>
               <div class="form-group">
                  <label for="password">Password</label>
                  <input type="password" id="password" name="password" placeholder="Enter your password" required>
               </div>
               <button type="submit">Sign Up</button>
            </form>
            <p>Already have an account? <span onclick="toggleForms()" class="toggle-text">Login</span></p>
         </div>
         <div class="signup-right"></div>
      </div>
   </div>

   <script src="{% static 'js/start.js' %}"></script>
</body>
</html>

this is my start.css:

/* Colors for reference: 9A3B3B, C08261, E2C799, F2ECBE */
body, html {
  height: 100vh;
  width: 100vw;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: Arial, sans-serif;
}

.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  background-color: #F2ECBE;
  overflow: hidden; 
}

/* Default form styling */
.form {
  display: none; /* Initially hidden */
  width: 100%;
  height: 100%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  position: absolute;
  overflow: hidden; 
  transition: transform 0.6s ease-in-out;
}

/* Show the active form */
.form.active {
  display: flex;
  animation: slide-in 0.6s forwards;
}

.form-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 5%;
    width: 100%;
    animation: fade-in 0.6s;
}

/* Left section with background */
.login-left, .signup-right {
  width: 70%;
  background-color: #9A3B3B;
}

/* Right section */
.login-right, .signup-left {
  width: 30%;
  background-color: #F2ECBE;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 5%;
}
/* Sliding Animation for Forms */
@keyframes slide-in {
  0% { transform: translateX(100%); }
  100% { transform: translateX(0); }
}

/* Text Animation */
@keyframes fade-out {
  0% { opacity: 1; transform: translateX(0); }
  100% { opacity: 0; transform: translateX(-50px); }
}

@keyframes fade-in {
  0% { opacity: 0; transform: translateX(50px); }
  100% { opacity: 1; transform: translateX(0); }
}

.form-title, .toggle-text {
  animation: fade-in 0.6s;
}

/* Form elements styling */
.form-group {
  margin-bottom: 15px;
  width: 80%;
  text-align: left;
}

.form-group label, button {
  display: block;
  font-size: 14px;
  margin-bottom: 5px;
}

button {
  width: 80%;
  padding: 10px;
  font-size: 16px;
  color: #F2ECBE;
  background-color: #AD5F4E;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #AD5F4E;
}

.toggle-text {
  color: #AD5F4E;
  cursor: pointer;
  text-decoration: underline;
  margin-top: 10px;
}

/* Slide in SIGNUP from the left */
@keyframes signup-slide-in-from-left {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(0); }
}

/* Slide out SIGNUP to the right */
@keyframes signup-slide-out-to-right {
  0% { transform: translateX(0); }
  100% { transform: translateX(100%); }
}

/* Slide in LOGIN from the right */
@keyframes login-slide-in-from-right {
  0% { transform: translateX(100%); }
  100% { transform: translateX(0); }
}

/* Slide out LOGIN to the left */
@keyframes login-slide-out-to-left {
  0% { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}

/* Ensure each animation holds its final position */
.form {
  animation-fill-mode: forwards;
}

and this is start.js:

function toggleForms() {
  const loginForm = document.getElementById('loginForm');
  const signupForm = document.getElementById('signupForm');
  const container = document.querySelector('.container');
  const title = document.querySelectorAll('.form-title');
  const toggleText = document.querySelectorAll('.toggle-text');

  if (loginForm.classList.contains('active')) {
      // LOGIN slides out to the left, SIGNUP slides in from the left
      loginForm.style.animation = 'login-slide-out-to-left 0.6s forwards';
      signupForm.style.animation = 'signup-slide-in-from-left 0.6s forwards';
      container.style.backgroundColor = '#F2ECBE'; // Green background for this transition
  } else {
      // SIGNUP slides out to the right, LOGIN slides in from the right
      loginForm.style.animation = 'login-slide-in-from-right 0.6s forwards';
      signupForm.style.animation = 'signup-slide-out-to-right 0.6s forwards';
      container.style.backgroundColor = '#9A3B3B'; // Blue background for this transition
  }

  // Fade out text
  title.forEach(el => el.style.animation = 'fade-out 0.4s forwards');
  toggleText.forEach(el => el.style.animation = 'fade-out 0.4s forwards');

  setTimeout(() => {
      // Toggle active form
      loginForm.classList.toggle('active');
      signupForm.classList.toggle('active');

      // Reset animations
      loginForm.style.animation = '';
      signupForm.style.animation = '';

      // Fade text back in
      title.forEach(el => el.style.animation = 'fade-in 0.6s forwards');
      toggleText.forEach(el => el.style.animation = 'fade-in 0.6s forwards');
  }, 400);
}

// Initialize the active form on page load
document.addEventListener("DOMContentLoaded", function() {
  document.getElementById('loginForm').classList.add('active');
});

When I press Login in Sign up form, it slides to the right, I see #9A3B3B background. And Login slides from the right (outside the monitor). It is correct.

When I press Register in Login form. Login form slides to the left.
I see #F2ECBE background and then SIGNUP forms slides from the right.
But it’s not correct. I want SIGN UP slides from the left outside the monitor.

I prompted to ChatGPT several times, but it can’t solve the issue.
Help me, please, PEOPLE.

Javascript/Jquery scroll event to move screen height triggers twice

Creating an autoscroll event to next slide/page of the size of the window. But every time I scroll, the event is triggered twice. I’m guessing because is detecting the autoscroll event as a trigger too and scrolling again. Is there a way to fix it?

        var content = 0;
        var scrolled = 0;
        var contentNum = $('.content').length
        var offset = $("#intro").offset();
        var lastScrollTop = 0;
 
        var timeout;

        $(window).scroll(function() {
            var st = $(this).scrollTop();
            var scrolled = 0;

            clearTimeout(timeout);  
            timeout = setTimeout(function() {
                if (st > lastScrollTop){
                    scrolled = 1;
                } else {
                    scrolled = -1;
                }

                if ( !(content == 0 && scrolled == -1) && !(content == (contentNum-1) && scrolled == +1) ){
                    content = content + scrolled;
                    offset = $(".content").eq(content).offset();

                    $('html').animate({
                        scrollTop: offset.top,
                        scrollLeft: offset.left
                    }, 500);

                }

                lastScrollTop = st;

            }, 50);

            
        });

Tried using global variable, but its still triggering twice.

Paragraph textContent disappear after flashing its value momentarily

I am learning how to handle files with multer, to do this i wrote a simple code that takes the uploaded file, parse it to an api that retrieves the the data from the text file and returns the said data, after that i simple modify the paragraph’s text content to be this data from the file.
The problem is that text content flashes for a moment and then the page returns to its prior form. I reckon the web page refreshes after the form submission despite me adding preventDefault();
Please help me understand what i did wrong.
I am a beginner so go easy on me if i made a silly mistake.
I am attaching coding from all the files below:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FILE HANDLING</title>
</head>
<body>
    <h1>Upload a file below</h1>
    <!-- action="http://localhost:3000/upload" -->
    <form method="post" enctype="multipart/form-data" id="FileSubmitForm">
        <label for="FileInput">Upload a file: </label>
        <input type="file" id="FileInput" name="file" required>
        <button type="submit">Upload</button>
    </form>
    <p id="displayContent">To be changed</p>
    <script src="file.js"></script>
</body>
</html>

file.js:

document.getElementById("FileSubmitForm").addEventListener("submit", (event)=>{
    event.preventDefault();
    console.log("form submission prevented");
    // event.stopPropagation();

    const fileInput = document.getElementById("FileInput");
    const formData = new FormData();
    formData.append("file", fileInput.files[0]);

    fetch('http://localhost:3000/upload', {
        method: 'POST', 
        body: formData
    })
        .then((response)=>response.json())
        .then((data)=>{
            console.log("success, server response:");
            console.log(data)
            console.log("This is what we are changing the content with");
            let newText = data.result;
            console.log(newText);
            document.getElementById('displayContent').textContent = newText;
            // document.getElementById('displayContent').style.display = 'block';
        })
        .catch((err)=>{
            console.error("Error", err);
        });
});

apifile.js:

const express = require('express');
const cors = require('cors');
const fs = require('fs');
const multer = require('multer');

const app = express();
app.use(cors());

// if(!fs.existsSync('./uploads')){
//     fs.mkdir('./uploads');
// }

const upload = multer({ dest: 'uploads/' }); // Configure multer to store files in the 'uploads' directory

app.post('/upload', upload.single('file'), (req, res) => {
    const file = req.file;
    console.log(req.file);
    if (!file) {
        return res.status(400).json({ result: 'No file uploaded' });
    }

    // Read the file contents
    fs.readFile(file.path, 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            return res.status(500).json({ result: 'Error reading file' });
        }
        
        res.status(200).json({ result: data });
    });
});

app.listen(3000, () => {
    console.log('API is running on http://localhost:3000');
});

I tried using preventDefault() but it doesn’t work

Issues to run the react project-How can I fix it?

I have a telemedicine project developed with React.js, and I’m seeking your expertise to address some challenges I’m encountering. The project exhibits inconsistent behavior:

It occasionally runs smoothly on Windows OS, but there are instances where it fails to execute properly.
Command Prompt works reliably, while PowerShell shows issues.
I’m facing compatibility problems with both Ubuntu and macOS as well.
I’m uncertain whether these issues stem from the OS environment or other underlying factors.

If you’re passionate about tackling cross-platform challenges and have experience in ensuring robust application performance, I would love for you to check out the project here: https://github.com/Awesome1206/Project.

Your insights could be invaluable in helping to enhance this project! Thank you!

I tried to run the project on windows( 10, 11), Ubuntu and MacOs.

Is a simple (no function declarations) TypeScript expression automatically a valid JS expression?

TypeScript code requires transpilation into JS.
But are expressions (that is anything that is valid as a right hand side of an assignment) also required to be transpiled?

Obviously a function (with type decorators) can appear as expressions and require transpilation:

const f = ():int => 42;

The return type decoration is TS specific and makes the expression ():int => 42 an invalid JS expression.

My question is more specific toward expressions that return a primitive type. And again, I can embed a TS function into the expression just for the kicks and that is obviously not JS compliant:

const x = (():int => 42)();

If the expression is “plain sequence of operators, literals and variables” without any deviation into function declarations, are there TS extensions that can appear?

PS. there are expressions that require functions, eg. somearray.map((x:int)=>x+1) and the expression is TS not JS, but again this is because the function type decorators come into play. I’m looking for examples that do not involve functions, lambdas and the associated type decoration.

How to write a port forwarding program with Bun

I encountered some issues while implementing port forwarding using the TCP Socket API in Bun.

When you attempt to send packets to a Bun TCP server located at a non-local address, it results in the received data being different from what was sent.

For more details, please see [Ikaleio/portforwarding_test](https://github.com/Ikaleio/portforwarding_test), where [portforwarding_test/blob/main/bun_socket.ts](https://github.com/Ikaleio/portforwarding_test/blob/main/bun_socket.ts) is my Bun forwarding implementation.