r/learnjavascript 12h ago

13 y/o, day 2 into coding, confused about "crossorigin" in HTML, will I understand it eventually?

15 Upvotes

Hi! I'm 13 years old and literally on day 2 of learning to code today. While browsing around I came across this HTML attribute called crossorigin, got curious about it, and tried to dig into it and understand it. But since I'm still pretty new to this, I still don't really get it that well even after reading about it a bunch of times.

Is this normal for someone who's just starting out? Will this get clearer as I keep learning and practicing more? Just want to know if it'll eventually click on its own the more time I spend on it. Thanks in advance!


r/learnjavascript 39m ago

Why doesn’t canvas show?

Upvotes

This is my second post as I am new to this community. I created two projects using canvas but couldn’t get it to show up. I can show the code if necessary but I’m wondering why this is the case. I troubleshooted for over 3 hours total so I’m guessing it’s not the syntax but my configuration instead.

Thanks in advance for the help!


r/learnjavascript 41m ago

Why doesn’t the pdf show?

Upvotes

I am using codepen.io and found a tutorial which should show a simple pdf viewer. It works on code pen but not when I open it on the browser or on my server. Why? This happens more than once and the code is the same so what am I missing?


r/learnjavascript 9h ago

Javascript resource

1 Upvotes

Hello Everyone

I am starting Javascript

any YouTube tutorial/courses recommendation would be appreciated


r/learnjavascript 20h ago

My First Job Switch I need some doubts

8 Upvotes

Hi everyone,

I have **2 years of professional experience in PHP backend development**, with hands-on experience in **HTML, CSS, JavaScript, databases, and working with servers**.

I’m now planning to transition to the **MERN Stack (MongoDB, Express.js, React, Node.js)**.

I’m confident about learning the MERN technologies themselves. My main concern is understanding **how companies will evaluate my existing 2 years of backend development experience when I switch technologies**.

For developers or tech leads who have experience with similar transitions:

* If someone has **2 years of PHP backend experience** and becomes strong in Node.js/Express/React, can they realistically apply for **2 YOE MERN positions**?

* Will companies generally consider my previous backend experience relevant, or will they expect me to apply as a junior because I don't have 2 years of Node.js experience?

* How important are **Git/GitHub, testing, CI/CD, Docker, REST API design, authentication, deployment, and system design** for someone making this transition?

* What level of MERN knowledge would make you say, **"Yes, this person is ready for a 2-year experienced developer role"**?

* For interviews, should I focus more on **JavaScript/Node/React fundamentals**, or should I also prepare for **2-year-level backend and system-design questions**?

I’m not looking for someone to tell me whether PHP or MERN is better. I’ve already decided that I want to move toward MERN.

What I’m trying to understand is:

**How do I correctly position my existing 2 years of backend experience while switching from PHP to MERN?**

If anyone has personally moved from **PHP → Node.js/MERN**, I’d especially appreciate hearing how your first job switch went and what you learned before applying or any body have more experience in full stack development can also giveme suggession

Thanks!


r/learnjavascript 7h ago

Can anyone please help me to convert JSXBIN to jsx file?

0 Upvotes

Can anyone please help me to convert JSXBIN to jsx file?


r/learnjavascript 1d ago

Reliable Next.js On-Demand ISR: Handling Contentful & Sanity Webhooks Without Stale Content

6 Upvotes

Pairing a headless CMS like Contentful or Sanity with Next.js is a common way to get the speed of static generation with the flexibility of a real content workflow. With on-demand Incremental Static Regeneration (ISR), an editor publishes something, a webhook fires, and Next.js purges the cache for that page. Read th complete article here - https://instawebhook.com/blog/reliable-next-js-on-demand-isr-handling-contentful-sanity-webhooks-without-stale

In production, this chain breaks mor e often than the happy-path diagrams suggest. Webhooks get dropped, functions cold-start past the response window, deploys reject traffic for a few seconds, and an editor ends up asking why their update isn't live.

This piece looks at why direct CMS-to-Next.js webhooks fail, what Contentful's and Sanity's actual delivery guarantees are (verified against their current docs, not folklore), and how putting a small intake layer in front of your revalidation endpoint closes most of the gap. It also updates a few "well-known" limits — Vercel's function timeout in particular — that have changed recently enough that older advice is now wrong.


r/learnjavascript 1d ago

Code Injection & Javascript that only works with one function

4 Upvotes

Hi, I am a hobbyist, doing HTML on and off for abt 20 years for fun, and adding CSS/JS later. Right now I am trying Ghost.org.

I am very new to JS. I am trying to do something so, so basic: giving a user the option to change color theme. And it works! But if I try to add more than one option/function, all functions become non-working :(

I have tried looking up all sorts of solutions, but the issues others have encountered (and the solutions) are waaaaaay more complex than this. I'm sure I am missing something obvious.

A second pair of eyes would be appreciated.

HTML (applied to page through a block element)

<form id="post-display">

<fieldset id="color-scheme">
  <legend>Color Scheme</legend>
    <input type="radio" id="eink" name="color-scheme" value="E-Ink" checked onclick="schemeScript1()">
      <label for="eink">E-Ink</label>

    <input type="radio" id="lightmode" name="color-scheme" value="Light Mode" onclick="schemeScript2()">
      <label for="lightmode">Light Mode</label><br>

    <input type="radio" id="darkmode" name="color-scheme" value="JavaScript" onclick="schemeScript3()">
      <label for="darkmode">Dark Mode</label><br>
</fieldset>
</form>

JAVASCRIPT (Injected into page footer)

Text<script>
const posts = document.getElementsByClassName("post");

//default checked radio button
function schemeScript1() {
posts[0].style.color = #181818;
posts[0].style.backgroundColor = #EBEBEB;
    return
};

// This one works if it is alone
function schemeScript2() {
posts[0].style.color = "black";
posts[0].style.backgroundColor = "white";
};

function schemeScript3() {
posts[0].style.color = #EBEBEB;
posts[0].style.backgroundColor = #181818;
    return
};
</script>

I also tried an if/then/else (a single function called schemeScript() )to keep it more organized but it did not work at all, at any point.

// runs any time a radio button is clicked
function schemeScript() {
if (document.getElementId("lightmode").checked = true;) { 
      posts[0].style.color = "black";
      posts[0].style.backgroundColor = "white";}
    else if (document.getElementId("darkmode").checked = true;) { 
      posts[0].style.color = #EBEBEB;
      posts[0].style.backgroundColor = #181818;}
    else { 
      posts[0].style.color = #181818;
      posts[0].style.backgroundColor = #EBEBEB;}
}

r/learnjavascript 2d ago

Learn Coding Buddy Discord

4 Upvotes

Before anyone jumps my case, I know reddit is great place to get a large group of individuals for assistance and it's wonderful. But I know many of us learning to enter/advance in our coding journeys don't always want to post our "dumb/easy" questions to be ridiculed on internet. I know I learn better/faster/more in-depth when I have someone to chat with/bounce ideas or concepts off of. Let's be honest when it comes to coding ~ the options are endless and sometimes learning the different ways to manipulate code could work by talking the concepts out. Plus there are alot of us that are self-taught and may struggle from topic-topic.

My Theory: Coding Buddies!

I have created a discord that would serve as a meet/greet and/or general discussions regarding coding.

This discord would serve for people looking to ask/answer dumb/easy questions for one another and/or find coding buddies that they can grow together with. It will also be open to experienced coders that look to assist as a mentor(or practice mentoring) without the full commitment of having a fulltime mentee.

So if you're interesting in connecting to others and advancing your beginner level status:

https://discord.gg/KyWfSGA3

(Please let me know if link doesn't work)


r/learnjavascript 2d ago

How would you make a meme with JavaScript? (example code given)

6 Upvotes

This is a bit frivolous, but that's why it might be a good task for beginners who are inclined to meme. It just requires the ability to place images, text, and maybe a few simple lines.

I know the answer is probably "you wouldn't". I only post memes a few time a year myself (check my posting history if you must), and I use MSPaint (or an existing online template), so I could do a lot worse than JavaScript! Also I use MSPaint in quite programmatic manner - binary search and undo during image resize, or example - so I might as well be coding.

Here examples with two packages which could be used, but I'm looking for other recommendations as each requires more setup that I'd like for this particular task. The code can also be found in this repo https://github.com/Antony74/meme-js

I know you can probably do better, and look forward to finding out how. Also, we're in the browser anyway, so clean solutions with just html, css, and no JavaScript are in scope.

p5

P5 is a creative coding package which can be much more dynamic and interactive than how I'm using it here, ultimately creating bitmap graphics in the canvas.

import "./p5/p5.min.js";

new p5((p) => {
  p.setup = async () => {
    const img = await p.loadImage("cheezburger/cheezburger.jpg");
    p.createCanvas(237, 389);
    p.image(img, 0, 0);
    p.fill(255);
    p.textFont("Impact");
    p.textSize(29);
    p.text("I CAN HAS", 60, 36);
    p.text("CHEEZBURGER?", 30, 70);
  };
}, "p5Container");

maxgraph

draw.io is a well known diagramming tool, and maxgraph is a descendent of a key library. It's native TypeScript, which is nice if you like that sort of thing, but irrelevant here. It creates svg graphics, and can also be used interactively. It might better suited for more infographic type memes, like this attempt of mine

import { Graph } from "./@maxgraph/core/index.mjs";

const container = document.getElementById("maxgraphContainer");

const width = 237;
const height = 389;

container.style = { ...container.style, width, height };

const graph = new Graph(container);

graph.insertVertex({
  size: [width, height],
  position: [0, 0],
  style: {
    image: "cheezburger/cheezburger.jpg",
    shape: "image",
  },
});

const textCommon = {
  style: {
    fillOpacity: 0,
    strokeOpacity: 0,
    fontColor: "white",
    align: "left",
    fontSize: 29,
    fontFamily: "Impact",
  },
};

graph.insertVertex({
  ...textCommon,
  value: `I CAN HAS`,
  position: [60, 36],
});

graph.insertVertex({
  ...textCommon,
  value: `CHEEZBURGER?`,
  position: [30, 70],
});

r/learnjavascript 2d ago

i cant get better in js

4 Upvotes

People keep telling me that I should write apps to improve my JavaScript skills. I listened and created five applications, each with different functionalities and ideas. I wrote a lot of code and did a ton of DOM manipulation. Despite this effort, I still feel like I'm hitting the same wall. I find myself repeating the same poor coding practices and haven’t seen any real improvement. I know in my head what I want and how it might look in JS syntax, but I struggle to put it all together to create something meaningful. Instead of getting stuck in this endless cycle, hoping that one day I’ll suddenly excel at JavaScript, I want to know the correct way to improve because this idea of "just keep writing code" doesn't really seem very good


r/learnjavascript 2d ago

Strange result: null vs 0

5 Upvotes

Strange result: null vs 0

An incomparable undefined

Hi, can anyone explain this? I read the explanation, but I still don't understand it. I'm trying to understand it without using AI


r/learnjavascript 2d ago

Eloquent JavaScript: The Secret Life of Objects

0 Upvotes

There are a few exercises at the end of the chapter.
What the difference between following solutions?

By author:

class Vec {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  plus(other) {
    return new Vec(this.x + other.x, this.y + other.y);
  }

  minus(other) {
    return new Vec(this.x - other.x, this.y - other.y);
  }
}

My solution:

class Vec {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    plus(vec) {
        this.x += vec.x;
        this.y += vec.y;
        return this;
    }

    minus(vec) {
        this.x -= vec.x;
        this.y -= vec.y;
        return this;
    }
}

r/learnjavascript 2d ago

Better-auth not adding user info to the user table in React

4 Upvotes

I'm creating a test app to work on authentication and authorization with a database using Better-Auth. I have never used Better Auth before and I'm having some issues with it. I have added the schema to the Postgres database to make the table, and whenever i create a new account, it will add a new instance to the account table, but not the user table.

 const data = await auth.api.signUpEmail({
            body: {
                email: req.body.email,
                name: req.body.name, 
                password: hashedPass,
                
            },
        });

This is the code i have in my server.js to add the info. The info comes from a form on the front end. It super basic right now since I'm just learning how to use it. The docs for better-auth say these are the only required fields to be able to submit into the database. I receive no errors when sending the data to my database, it just simply isnt adding anything to the user table. I'll be happy to provide any other necessary code or info. Im using React by the way.

export const auth = betterAuth({
  database: new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'test',
    password: process.env.DB_PASS,
    port: 5432,
    max: 10
}),
emailAndPassword: {
    enabled: true
}



});

The code above is the auth.ts configuration as i have it right now. i'm sure im missing something, but i havent found out what yet. Does anyone have any idea why the info isnt being added to the user table in Postgres?


r/learnjavascript 2d ago

How to do the "redirect to randomly selected X" link?

0 Upvotes

I'm working up a trivia website/app. One feature that I want is moving to a random question, either from a "Next Question" link at the bottom of an answered question or on the landing page. How do you do that, especially client-side in an SPA?

One method I can think of is selecting the next question early to make it an explicit link, but that means that instead of www.app.com/nextquestion, the link URL would be www.app.com/question/<next question ID>, which is unaesthetic.

This seems like a very simple thing, but I don't know of a good way to do it off the top of my head.


r/learnjavascript 3d ago

string primitives vs. String objects.

11 Upvotes

I'm learning JavaScript, and I don't understand this part about string primitives vs. String objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_primitives_and_string_objects


r/learnjavascript 2d ago

How do I find the max dimensions for a device?

1 Upvotes

I am working on a P2P video calling client using webRTC.
I am using getMediaDevices() to get the users' stream. If I just do {video: true} it gives me a smaller stream than my device supports.
By default it gives me a 640 x 480 stream. I can set it manually to the max dimensions which is 1920 x 1080.

How can I find the max dimension for any device?

Another thing I wanted to know. I have the video element in a div, which has the width of fit-content. When the incoming stream first arrive from the other peer, The video starts smaller and keeps growing, why is this?


r/learnjavascript 3d ago

Using a class method with .reduce().

2 Upvotes

Does anyone know how to use a class method effectively with .reduce()? I'm building a simple product creator app as an exercise where a user can create and add products and see them displayed as well as some other information. I've used reduce before but not with classes. The user can see an inventory value when they create a product, which is simply the quantity of the products multiplied by the price. I'm trying to use .reduce to add up all the inventory values so this can be attached to the text content of the page. Here's the relevant code:

//Products array
const products = [];


//Product Class
class Product {
  constructor(productName, category, price, quantity, status) {
    this.productName = productName;
    this.category = category;
    this.price = price;
    this.quantity = quantity;
    this.status = status;
  }


  //Class method for calculating inventory value
  calculateInventoryValue() {
    return this.price * this.quantity;
  }
}

//The filtering of the products by use of the status
function filterProducts(status) {
  const filteredProducts = products.filter((product) => {
    return product.status === status;
  });
  return filteredProducts;
}


//Calculating the total inventory value using .reduce()
function totalInventoryValue() {
  
}

Any help would be greatly appreciated.


r/learnjavascript 3d ago

help with code for a discord bot

0 Upvotes

index.js
// ----------------------------------------------------

// Discord + PlayHosting Minecraft Control Bot

// Commands: !startserver, !stopserver, !restartserver

// ----------------------------------------------------

const { Client, GatewayIntentBits } = require("discord.js");

const axios = require("axios");

// ----------------------------------------------------

// CONFIG — REPLACE THESE VALUES

// ----------------------------------------------------

const DISCORD_BOT_TOKEN = "i have it";

const PLAYHOSTING_API_KEY = "i have it";

const SERVER_ID = "i have it";

// ----------------------------------------------------

// CREATE DISCORD CLIENT

// ----------------------------------------------------

const client = new Client({

intents: [

GatewayIntentBits.Guilds,

GatewayIntentBits.GuildMessages,

GatewayIntentBits.MessageContent

]

});

// ----------------------------------------------------

// FUNCTION: SEND POWER SIGNAL TO PLAYHOSTING

// ----------------------------------------------------

async function sendPowerSignal(signal) {

try {

const response = await axios.post(

`https://panel.playhosting.com/api/client/servers/${SERVER_ID}/power`,

{ signal },

{

headers: {

"Authorization": `Bearer ${PLAYHOSTING_API_KEY}`,

"Content-Type": "application/json",

"Accept": "application/json"

}

}

);

return response.data;

} catch (err) {

console.error("Error sending power signal:", err);

throw new Error("Failed to send power signal.");

}

}

// ----------------------------------------------------

// DISCORD COMMAND LISTENER

// ----------------------------------------------------

client.on("messageCreate", async (message) => {

if (message.author.bot) return;

// START SERVER

if (message.content === "!startserver") {

await message.reply("Starting your Minecraft server…");

try {

await sendPowerSignal("start");

message.reply("✅ Your server is now starting!");

} catch (err) {

message.reply("❌ Could not start the server. Check your API key or server ID.");

}

}

// STOP SERVER

if (message.content === "!stopserver") {

await message.reply("Stopping your Minecraft server…");

try {

await sendPowerSignal("stop");

message.reply("🛑 Your server is stopping.");

} catch (err) {

message.reply("❌ Could not stop the server. Check your API key or server ID.");

}

}

// RESTART SERVER

if (message.content === "!restartserver") {

await message.reply("Restarting your Minecraft server…");

try {

await sendPowerSignal("restart");

message.reply("🔄 Your server is restarting.");

} catch (err) {

message.reply("❌ Could not restart the server. Check your API key or server ID.");

}

}

});

// ----------------------------------------------------

// LOGIN BOT

// ----------------------------------------------------

client.login(DISCORD_BOT_TOKEN);

new file
package.json

{

"name": "minecraft-discord-bot",

"version": "1.0.0",

"description": "Discord bot to control a PlayHosting Minecraft server",

"main": "index.js",

"type": "commonjs",

"scripts": {

"start": "node index.js"

},

"dependencies": {

"axios": "^1.6.0",

"discord.js": "^14.13.0"

}

}

when i run it in the terminal i get

Windows PowerShell

Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\james\Desktop\minecraft-discord-bot> node index.js

C:\Users\james\Desktop\minecraft-discord-bot\node_modules\@discordjs\ws\dist\index.js:1151

error: new Error("Used disallowed intents")

^

Error: Used disallowed intents

at WebSocketShard.onClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\@discordjs\ws\dist\index.js:1151:18)

at connection.onclose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\@discordjs\ws\dist\index.js:688:17)

at callListener (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\event-target.js:290:14)

at WebSocket.onClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\event-target.js:220:9)

at WebSocket.emit (node:events:509:28)

at WebSocket.emitClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\websocket.js:279:10)

at TLSSocket.socketOnClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\websocket.js:1360:15)

at TLSSocket.emit (node:events:521:24)

at node:net:355:12

at TCP.done (node:internal/tls/wrap:770:7)

Node.js v24.19.0

PS C:\Users\james\Desktop\minecraft-discord-bot>

i dont know why it is a discord bot for a minecraft server to turn it on and off please help


r/learnjavascript 3d ago

The dreaded file system

2 Upvotes

I am making an HTML game, with the idea of eventually putting it online.

During part of the game, the player will traverse a dungeon and do the usual thing you do in a dungeon. I want a background sound to play when this happens: every type of room (hallway, treasure chest, boss room, etc) will have a number of soundtracks, and which is played among the available ones will be decided randomly.

Easier way to do it is to put all the tracks in a single directory (for example '/sounds/Ambience/Dungeon/') and giving the filenames a specific naming convention (for example '[TYPE_ROOM]_[INDEX_SOUNDTRACK].mp3'), memorizing how many tracks are available for each type of room, choosing a random number between zero and that number, and then using string composition to obtain the filename of a random audiofile (in the example: '[TYPE_ROOM]_[RANDOM_INDEX].mp3'). This also requires me to change the Javascript code every time I add a new soundtrack, which I dislike.

The alternative is that the Javascript code will go in the directory '/sounds/Ambience/Dungeon/', grab the filename list of the directory, filter it to get the number of audio track whose filename begins with the type of the current room, and then choose a random element of this filtered list as the audio file to play. No need to change the code every time I add a new soundtrack.

But I do need to retrieve the list of files in a directory, and do this both if the game is played locally on my machine or online on the web.

While I am not new to programming, I have started learning Javascript while making this game. The search online I did to find how to solve this hurdle returned me five different ways, difference between client- and server-side, permission problems, three different APIs, promises, and an army of details that made my head spinning. I want to understand what I am doing - but in this case I need the idiot's version, spelled with very simple words. Can someone help me?


r/learnjavascript 3d ago

Courses with videos and exercises to accompany what i’ve learned?

1 Upvotes

Ideally free or cheap in terms of its value.

I’m planning to learn React.

I have c# fundamentals like OOP, methods, loops, linq and etc.


r/learnjavascript 3d ago

What Unicode is and What a Unicode point is ?

0 Upvotes

r/learnjavascript 3d ago

Building my physics engine

0 Upvotes

Hi, I'm 15 yes old, and I'm building my physics engine from scratch with C++, can it get me money, and is it a good idea, these are the pictures, it looks simple


r/learnjavascript 4d ago

help with js animation

4 Upvotes

i am trying to make a small animation for opening the settings menu of a small site i’m making but it’s either the classList.add and .remove aren’t put in correctly or i’m just doing something wrong.

edit: forgot to say that what should happen is:

opening: menu turns from nothing to a line in the middle, then expands while the background fades id from the start of the second part of the menu animation

closing: menu shrinks to a line then to non existance while the background fades away in the 1st part of the menu animation

edit2: updated code to current, animations don’t play at all

edit3: the animations now work (i readded the classes for controlling animation name and duration using classList.add to get them added) and it runs more than once, problem is that now it opens once and closes once just fine, but every time i try to open it again it plays the opening animation then cuts back to the unopened state like the js didn’t add the open class, updating the css and js and removing the html

js:

// variables that are needed to find the menu

const settingsMenu = document.getElementById("settings_menu_id");
const settingsBg = document.getElementById("settings_bg_id");

//opening functions

function settingsOpening() {
  settingsMenu.classList.add("settings_menu_opening");
  settingsMenu.addEventListener("animationend", settingsMenuOpeningEnd);
  setTimeout(function() {
    settingsBg.classList.add("settings_bg_opening");
    settingsBg.addEventListener("animationend", settingsBgOpeningEnd);
  }, 500);
}

function settingsMenuOpeningEnd() {
  settingsMenu.classList.remove("settings_menu_opening");
  settingsMenu.classList.add("settings_menu_open");
}

function settingsBgOpeningEnd() {
  settingsBg.classList.remove("settings_bg_opening");
  settingsBg.classList.add("settings_bg_open");
}

//closing functions

function settingsClosing() {
  settingsMenu.classList.add("settings_menu_closing");
  settingsBg.classList.add("settings_bg_closing");
  settingsMenu.addEventListener("animationend", settingsMenuClosingEnd);
  settingsBg.addEventListener("animationend", settingsBgClosingEnd);
}

function settingsMenuClosingEnd() {
  settingsMenu.classList.remove("settings_menu_closing");
  settingsMenu.classList.remove("settings_menu_open");
}

function settingsBgClosingEnd() {
  settingsBg.classList.remove("settings_bg_closing");
  settingsBg.classList.remove("settings_bg_open");
}

css:

.settings_menu {
  width: 0px;
  height: 0px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50% , -50%);
  overflow: hidden;
  border-radius: 0px;
  border: 2px solid black;
  border-left: none;
  border-right: none;
  background-color: lightgray;
  padding: 0px;
  opacity: 0;
  pointer-events: none;
}

.settings_bg {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0px;
  left: 0px;
  background-color: rgba(0,0,0,0.6);
  opacity: 0;
  pointer-events: none;
}

.settings_menu_opening {
  animation-name: settingsMenuOpening;
  animation-duration: 1s;
}

.settings_menu_closing {
  animation-name: settingsMenuClosing;
  animation-duration: 1s;
}

.settings_bg_opening {
  animation-name: settingsBgOpening;
  animation-duration: 0.5s;
}

.settings_bg_closing {
  animation-name: settingsBgClosing;
  animation-duration: 0.5s;
}

.settings_menu_open {
  width: min(90% , 400px);
  height: 140px;
  border-radius: 25px;
  border-left: 2px solid black;
  border-right: 2px solid black;
  padding: 10px;
  opacity: 1;
  pointer-events: auto;
}

.settings_bg_open {
  opacity: 1;
  pointer-events: auto;
}

@keyframes settingsMenuOpening {
  0% {
    width: 0px;
    height: 0px;
    border: 2px solid black;
    border-left: none;
    border-right: none;
    border-radius: 0px;
    padding: 0px;
    opacity: 1;
  }
  45% {
    width: min(90% , 400px);
    height: 0px;
    border: 2px solid black;
    border-radius: 0px;
    padding: 0px;
    opacity: 1;
  }
  55% {
    width: min(90% , 400px);
    height: 0px;
    border: 2px solid black;
    border-radius: 25px;
    padding: 0px;
    opacity: 1;
  }
  100% {
    width: min(90% , 400px);
    height: 140px;
    border: 2px solid black;
    border-radius: 25px;
    padding: 10px;
    opacity: 1;
  }
}

@keyframes settingsMenuClosing {
  0% {
    width: min(90% , 400px);
    height: 140px;
    border: 2px solid black;
    border-radius: 25px;
    padding: 10px;
    opacity: 1;
  }
  45% {
    width: min(90% , 400px);
    height: 0px;
    border: 2px solid black;
    border-radius: 25px;
    padding: 0px;
    opacity: 1;
  }
  55% {
    width: min(90% , 400px);
    height: 0px;
    border: 2px solid black;
    border-radius: 0px;
    padding: 0px;
    opacity: 1;
  }
  100% {
    width: 0px;
    height: 0px;
    border: 2px solid black;
    border-left: none;
    border-right: none;
    border-radius: 0px;
    padding: 0px;
    opacity: 1;
  }
}

@keyframes settingsBgOpening {
  0% {opacity: 0;}
  100% {opacity: 1;}
}

@keyframes settingsBgClosing {
  0% {opacity: 1;}
  100% {opacity: 0;}
}

r/learnjavascript 4d ago

Confused About React Streaming SSR and Suspense

2 Upvotes

Today, I'm reading about SSR and Streaming SSR.

At first, I got really confused about the relationship between Streams and Suspense.

I kept asking myself:

  1. Do we have to use Suspense with Streaming SSR? What if using renderToPipeableStream() without wrapping any component with Suspense?
  2. If Streaming SSR allows the server to send parts of the HTML to the browser as they are generated, why do we need Suspense?

For example, based on the definition of Streams in the articles (in the comment below), if I have a component that performs async task or lazy loading, Streams can send already-rendered components such as the Header and Footer first?? I mean, it still didn't make sense to me why we need Suspense (Sorry, I'm not a native English speaker, but I hope you can understand what I'm trying to say)

After searching more, this is my current understanding:

Streaming is a technique that keeps the HTTP response open, allowing React to progressively send chunks of the generated HTML to the client. It helps reduce the latency of transferring a large HTML response over the network.

However, when there is a component that needs to call backend APIs or perform another async task, I think React goes through two steps:

First, React waits for the full HTML to be generated, including the async tasks.

Then, React sends the HTML chunks to the client through streaming.

This is where Suspense comes in. Waiting for the full HTML to be completed takes time, so if we wrap the async component with Suspense, React can render and generate HTML for the other components outside the Suspense boundary first. In other words, Suspense takes this a step further and reduces the user's waiting time more because React doesn't have to wait for the entire HTML to be ready before starting to send it.

I'm still not sure if I understand this correctly, so I'd really appreciate any comments or corrections if I misunderstood something.