Do you know that, you can't render HTML in React using JSX? If you've ever tried doing something like this in React: const html = "<p>This is <strong>HTML</strong></p>"; <div>{html}</div> You’ll notice it just renders as plain text with tags displayed as it is. Because React escapes everything inside JSX by default for security reason. ✅ This prevents malicious code from running, and that's a good thing! But what if you actually need to render HTML coming from an API? then you need to write it like this: <div dangerouslySetInnerHTML={{ __html: html }} /> React has provided a prop with name of dangerouslySetInnerHTML where you can specify the html that you want to render. But as the prop name suggests, it's dangerous if not handled properly ❌ The html string might contain malicious script or code that can cause XSS attack, might read your cookies or do some other harm. So never use this way to render html content as a string. ✅ Best Practice: Combine These Two Tools Use DOMPurify and html-react-parser npm packages. → DOMPurify – Sanitizes HTML before rendering (removes all the XSS and dangerous script/html code) → html-react-parser – Converts sanitized HTML into real React components import DOMPurify from 'dompurify'; import parse from 'html-react-parser'; const cleanHTML = DOMPurify.sanitize(htmlString); <div>{parse(cleanHTML)}</div> ✨ This keeps your app secure while still letting you render dynamic HTML safely. TL;DR: ✅ You can't render HTML directly in JSX, and that’s a good thing. ✅ Use DOMPurify + html-react-parser combo instead of dangerouslySetInnerHTML. ✅ Always sanitize user-generated or untrusted content. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment
Yogesh Chavan’s Post
More Relevant Posts
-
Frontend devs have spent years writing #focus-trap #JavaScript for #modals. Handling #Tab, blocking #background clicks, adding #aria-hidden, installing libraries… all just to keep users inside a dialog. Meanwhile the browser quietly gave us a one-line solution: #inert Add inert to the background container and everything inside becomes completely non-interactive — no clicks, no focus, no screen readers, no tabbing. One attribute. Hundreds of lines of JS gone. I wrote a quick breakdown of how it works and where to use it (modals, sidebars, carousels, etc.) 👇 https://lnkd.in/e8WJGBwW #FrontendDevelopment #WebDevelopment #JavaScript #HTML #Accessibility #WebAccessibility #FrontendEngineering #WebPlatform #ModernWeb #SoftwareEngineering #CodingTips #FrontendDev #JavaScriptTips #DevCommunity #WebStandards
To view or add a comment, sign in
-
Day-22 What Are Web APIs in JavaScript? If JavaScript is single-threaded… Then how does this work? 👇 setTimeout(() => { console.log("Hello"); }, 2000); Or this? fetch("https://lnkd.in/dC3Rsk9V") .then(res => res.json()) .then(data => console.log(data)); JavaScript alone cannot do these things. 👉 These are powered by Web APIs. 🔹 What Are Web APIs? Web APIs are browser-provided features that JavaScript can use. They are NOT part of the JavaScript language itself. They are provided by: Chrome Firefox Safari Node.js (with its own APIs) 🔥 Common Web APIs ✔ setTimeout() ✔ setInterval() ✔ fetch() ✔ DOM APIs (document, querySelector) ✔ localStorage ✔ console All of these are provided by the browser environment. 🔥 How Web APIs Work with Event Loop Let’s understand flow 👇 console.log("Start"); setTimeout(() => { console.log("Timer Done"); }, 2000); console.log("End"); Execution Flow: 1️⃣ console.log("Start") → Call Stack 2️⃣ setTimeout → Goes to Web API 3️⃣ Timer runs in browser environment 4️⃣ After 2 seconds → Callback moves to Callback Queue 5️⃣ Event Loop pushes it to Call Stack (when empty) Output: Start End Timer Done 🔹 Important Understanding 👉 JavaScript Engine = Executes code 👉 Web APIs = Handle async operations 👉 Event Loop = Manages execution order Without Web APIs, async JS would not exist. 🔥 Node.js Has Its Own APIs In Node.js: setTimeout fs http process These are provided by the Node runtime — not the JS engine. Remeber for interview Question: Is setTimeout part of JavaScript? Answer: ❌ No ✅ It’s a Web API provided by the browser (or Node runtime) #JavaScript #WebAPI #EventLoop #AsyncJS #Frontend #LearnInPublic
To view or add a comment, sign in
-
Day 21🚀 #𝟯𝟬𝗗𝗮𝘆𝘀𝗼𝗳𝗰𝗼𝗱𝗶𝗻𝗴 HTML, CSS, BOOTSTRAP, JAVASCRIPT👨🏼💻 – Built a Speed Typing Test Web App! Today I created a Speed Typing Test using HTML, CSS (Bootstrap), and JavaScript. ✨ This small project helped me understand several important concepts in JavaScript and Web Development. Here are the key takeaways from today’s project 👇 💡 DOM Manipulation, Learned how to access and control HTML elements using document.getElementById() and dynamically update content on the page. ⏱️ Working with Timers, Implemented a timer using setInterval() to track how long a user takes to complete the typing test. 🌐 Fetching Data from an API, Used the fetch() method to get a random quote from an API and display it on the webpage. 🔄 Handling User Interactions, Added event listeners for Start, Submit, Reset buttons and keyboard actions to make the app interactive. ⌨️ Keyboard Event Handling, Used keydown events so pressing Enter automatically submits the typed text. 🧠 Conditional Logic, Compared the user’s typed text with the original quote to determine whether it is correct or incorrect. 🌀 Loading Indicators (Spinner), Displayed a loading spinner while fetching the quote from the API to improve user experience. 🧹 Reset Functionality, Implemented a reset button that clears the timer, input field, result message, and loads a new quote. ✨ Improving User Experience, Used Bootstrap components and simple styling to make the interface cleaner and more user-friendly. 📌 What I learned today: Building small projects is the best way to understand how JavaScript, APIs, and DOM manipulation work together in real-world applications. This is just the beginning — many more projects coming soon! 💻🔥 #WebDevelopment #CodingJourney #BuildInPublic #LearningByDoing #NxtWave #CCBP #Day21 #HTML #CSS #bootstrap #FrontendDevelopment #MiniProject #30DaysOfCode #MERN #JavaScript
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗙𝗎𝗍𝗎𝗿𝗲 𝗢𝗳 𝗪𝗲𝗯 𝗗𝗲𝗩𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝗧 You need to decide if your web application needs a JavaScript framework. HTMX and React are two different approaches. - HTMX is 14KB and extends HTML with attributes that make any element capable of issuing HTTP requests and swapping content without writing JavaScript. - React is 42KB and builds applications in the browser. The server sends JavaScript, and the browser executes it. Here are some key differences: - Weekly downloads: React has 96 million, HTMX has 94,000 - GitHub stars: React has 234,000, HTMX has 42,000 - Bundle size: React is 42KB, HTMX is 14KB - Language required: React needs JavaScript/TypeScript, HTMX works with any server language When to use each: - Use React for complex, interactive web applications that need rich client-side behavior - Use HTMX for server-rendered applications that need interactivity without JavaScript complexity The choice between HTMX and React depends on your application's needs. Consider how interactive your application needs to be. - If you need a simple, fast, and low-overhead solution, HTMX might be the better choice - If you need a complex, interactive application with rich client-side behavior, React might be the better choice Source: https://lnkd.in/grWaQ7Gu
To view or add a comment, sign in
-
Building things with React or other front-end frameworks has made development pretty smooth. They provide structure, reusable components, and make complex applications easier to manage. But not every project needs a framework, and knowing when not to use one is just as important. I realized this when I caught myself reaching for React even for simple and intermediate websites, pages that could have been built faster and shipped lighter with just HTML, CSS, and JavaScript. These technologies are powerful out of the box: • SEO-friendly by default (content is directly in HTML) • Extremely fast (no hydration or heavy JS) • Lower memory footprint (less JS running in the browser) • Simple and cheap hosting (can deploy on any CDN, no VPS required) • No build tools or complex setup • Full control and less abstraction What really changed my perspective was this blog: https://lnkd.in/gQKG6AwP What’s exciting about it is how people are building real, useful tools using just a single HTML file, no build step, no framework, no infrastructure. You can literally deploy apps by uploading one file. Frameworks are powerful, but knowing when to use them, and when the basics are enough, is a real skill.
To view or add a comment, sign in
-
What is non-blocking operation in JavaScript? Non-blocking in JavaScript means your code can start a slow task (like a timer, API call, or file read) and keep executing other code instead of waiting and freezing the main thread. Brief explanation JavaScript runs on a single thread with an event loop. When it hits an async operation (setTimeout, fetch, I/O), that work is offloaded to Web APIs / the system. When the async work finishes, its callback is queued and later pushed back to the call stack by the event loop, so the main thread never blocks while waiting. Simple example for your post js console.log("Start"); setTimeout(() => { console.log("Inside setTimeout (runs later)"); }, 2000); // 2 seconds console.log("End"); Output: Start End Inside setTimeout (runs later) Even though the timer is 2 seconds, "End" prints immediately. The setTimeout callback is handled in the background and executed later via the event loop, so the main thread is not blocked. Ready-to-post LinkedIn text JavaScript is single-threaded, but it still feels “non-blocking” thanks to the event loop.🧵 When we use functions like setTimeout, fetch, or other async APIs, JavaScript does not wait for them to finish. Instead, the heavy work is offloaded to the browser/Web APIs or Node’s libuv layer. Once the operation completes, its callback is pushed to a queue, and the event loop runs it when the call stack is free. Example: js console.log("Start"); setTimeout(() => { console.log("Inside setTimeout (runs later)"); }, 2000); console.log("End"); Output order: Start → End → Inside setTimeout (runs later) This is a simple demo of non-blocking behavior: while the timer is counting in the background, the main thread continues executing the rest of the code, keeping the UI responsive and allowing servers to handle many requests concurrently #javascript #frontendDevelopment #react #reactjs
To view or add a comment, sign in
-
𝑨 𝑹𝒂𝒏𝒅𝒐𝒎 𝑷𝒂𝒔𝒔𝒘𝒐𝒓𝒅 𝑮𝒆𝒏𝒆𝒓𝒂𝒕𝒐𝒓 𝒃𝒖𝒊𝒍𝒕 𝒘𝒊𝒕𝒉 𝑯𝑻𝑴𝑳, 𝑪𝑺𝑺, 𝒂𝒏𝒅 𝑱𝒂𝒗𝒂𝑺𝒄𝒓𝒊𝒑𝒕! Still in the middle of my web development course and this is one of the projects we built along the way. No frameworks, no libraries — just three clean, separate files and a lot of problem-solving. The UI is simple: pick your character types, set your length, hit generate. But the logic underneath is what made this project genuinely fun to build. One thing I didn't expect to think about randomly sampling from a mixed character pool doesn't actually guarantee every selected type shows up in the result. So I added a mandatory inclusion step for each selected set, then shuffle everything using the Fisher-Yates algorithm. Small detail, big difference. The project supports uppercase, lowercase, numbers, and special characters with a password length range of 8 to 20 characters. Files are kept separate for clean, readable, maintainable code exactly the habit I want to build early. Still learning, still growing and honestly loving every bit of it. Shoutout to Ma'am Juhinah Batool for making this course so engaging! GitHub: https://lnkd.in/dNkGbUX9 Medium: https://lnkd.in/dhFAhXDc #JavaScript #WebDevelopment #HTML #CSS #FrontendDevelopment #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
💡 JavaScript Concept Every Developer Should Understand — this One concept that often confuses beginners in JavaScript is the this keyword. A simple way to understand it is by remembering 4 basic rules. 🚀 The 4 Rules of this in JavaScript 1️⃣ Global Context Rule If this is used outside any function, it refers to the global object. In browsers, the global object is window. console.log(this); Output: Window {. . .} So here: this → window 2️⃣ Object Method Rule When a function is called using an object, this refers to that object. const person = { name: "Rahul", greet: function() { console.log(this.name); } }; person.greet(); Execution: person.greet() So: this → person Output: Rahul 3️⃣ Normal Function Rule If a function is called normally (not through an object), this refers to the global object (window) in browsers. function show() { console.log(this); } show(); Execution: show() So: this → window 4️⃣ Arrow Function Rule Arrow functions do not create their own this. They inherit this from the surrounding scope. const obj = { value: 10, show: function() { const arrow = () => { console.log(this.value); }; arrow(); } }; obj.show(); Here: this → obj Output: 10 🧠 Simple way to remember GLOBAL SCOPE │ ├── Normal function → this = window │ OBJECT METHOD │ ├── this = object │ ARROW FUNCTION │ └── this = inherited from parent #JavaScript #WebDevelopment #CodingConcepts #FrontendDevelopment #LearnToCode
To view or add a comment, sign in
-
🚀 Most of us add <script> tags… but rarely think about what they do to rendering. While diving deeper into browser fundamentals, I recently explored: 👉 Async vs Defer in JavaScript And it completely changed how I look at script loading. 🧱 What Happens with a Normal <script>? By default: <script src="app.js"></script> The browser: 1️⃣ Stops parsing HTML 2️⃣ Downloads the script 3️⃣ Executes it immediately 4️⃣ Then resumes parsing This blocks the Critical Rendering Path and can delay First Paint. ⚡ How async Works <script src="analytics.js" async></script> -Downloads in parallel with HTML parsing -Executes immediately once downloaded -Does not guarantee execution order Best for: -Analytics -Ads -Third-party independent scripts Because execution timing doesn’t matter. ⏳ How defer Works <script src="app.js" defer></script> -Downloads in parallel -Executes after HTML parsing completes -Maintains execution order Best for: -Main application bundles -Scripts that depend on DOM being ready This makes it more predictable for structured applications. 🎯 So Which One Should We Use? In modern applications: defer is more commonly used for app logic because it preserves order and avoids blocking parsing. async is great for independent scripts that don’t rely on DOM structure. Understanding this directly impacts: -Load performance -Rendering behavior -Core Web Vitals -Debugging timing-related issues The more I study browser behavior, the more I realize: React runs after the browser finishes its job. Optimizing script loading is part of real frontend engineering. #frontend #javascript #webperformance #reactjs #interviewprep
To view or add a comment, sign in
-
-
If JavaScript was originally designed to run in browsers… how are we able to run it outside the browser using Node.js? Most people first encounter JavaScript inside the browser console. The browser downloads a JS file and executes it using a JavaScript engine (like V8 in Chrome). That engine reads the code and runs it line by line. But the browser is not the language itself. JavaScript is just a programming language. What actually runs the code is a JavaScript engine. Node.js simply takes the same JavaScript engine (V8) and runs it outside the browser. So instead of executing JavaScript inside Chrome, Node.js allows us to execute JavaScript directly on our computer. This means JavaScript is no longer limited to client-side work. With Node.js we can build servers, APIs, CLI tools, automation scripts, and backend applications. In simple words: • Browser = Environment to run JavaScript for web pages • Node.js = Environment to run JavaScript outside the browser But there is an important difference between running JavaScript in the browser console and running it in Node.js. Browser JavaScript environment provides APIs related to the web page such as: • window • document • DOM manipulation • alert() • localStorage These APIs exist because the browser is designed to manage web pages. Node.js, on the other hand, provides APIs related to the operating system and server environment such as: • file system (fs module) • path handling • process information Because of this, code that manipulates the DOM will work in the browser but not in Node.js. Example: document.getElementById("title") This works in the browser because the browser has a DOM. But in Node.js there is no DOM, so this code will not work. Instead Node.js gives access to things browsers do not allow, like reading files: const fs = require("fs") This difference is the key idea: Browser JavaScript focuses on interacting with the webpage. Node.js focuses on interacting with the system and building backend applications. Same language. Different environments. #javascript #nodejs Hitesh Choudhary Chai Aur Code #chaicode #chaiaurcode
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development