Logo

dev-resources.site

for different kinds of informations.

Passing variables from the static page to the widget

Published at
12/23/2024
Categories
widget
react
programming
typescript
Author
ruturajmaggirwar
Author
16 person written this
ruturajmaggirwar
open
Passing variables from the static page to the widget

Introduction

Widgets are powerful ways to embed interactive functionality into static web pages. They allow developers to build modular components that can be reused across multiple websites, reducing redundancy and improving maintainability. One common scenario in widget implementation is the need to pass variables—such as configuration settings, API keys, or user-specific data—from the static page to the widget.

In this blog, we’ll explore how to securely pass variables from a static page to a widget, outline common use cases, and provide practical implementation examples.

Image description


Why Pass Variables from a Static Page to a Widget?

Imagine creating a reusable chat widget, analytics widget, or payment module. These widgets may require data such as:

  • A unique key or token for authentication.
  • User-specific IDs for personalization.
  • Random numbers for ensuring unpredictability or preventing cache collisions.

By passing variables dynamically, developers can:

  • Adapt widgets to different contexts.
  • Simplify widget reuse across multiple websites.
  • Reduce hard coding and enhance maintainability.

Implementation: Passing Variables Step-by-Step

  • Create the Static HTML Page - first, generate a random number dynamically using JavaScript and assign this number to a data attribute of the where the widget will render.
  • So modify the html file accordingly:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random Number Widget</title>
  <script>
    document.addEventListener("DOMContentLoaded", function () {
      const randomNumber = Math.floor(Math.random() * 1000);
      const widgetRoot = document.getElementById("widget-root");

      if (widgetRoot) {
        widgetRoot.setAttribute("data-random-number", randomNumber);
        console.log("Random number of the static page:", randomNumber);
      }
    });
  </script>
</head>
<body>
  <h1>Static Page with Random Number in Widget</h1>

  <!-- Div to hold the React widget -->
  <div id="widget-root"></div>

  <!-- Include the bundled React app -->
  <script defer="defer" src="bundle.min.js"></script>
</body>
</html>

  • In the React app, fetch the data-random-number attribute from the root element and change the code in the App.tsx file:
import { useEffect } from 'react';
import { Widget, addResponseMessage } from "react-chat-widget";
import "react-chat-widget/lib/styles.css";

function App() {
  useEffect(() => {
    const randomNumber = document.getElementById("widget-root")?
        .getAttribute("data-random-number");
    console.log("Random number from static page:", randomNumber);

    // Display the random number in the chat widget or use it as needed
    addResponseMessage(`Welcome! Your random number is: ${randomNumber}`);
  }, []);

  const handleNewUserMessage = (newMessage: string) => {
    console.log(`New message received: ${newMessage}`);
  };

  return (
    <Widget
      handleNewUserMessage={handleNewUserMessage}
      title="Random Number Widget"
      subtitle="Your session is unique!"
    />
  );
}

export default App;
  • Finally, bundle the Widget - Use Webpack to bundle the React widget into a bundle.min.js file, which can be included in the static page, and change the webpack.config.js file accordingly:
const path = require("path");

module.exports = {
  entry: path.join(__dirname, "src/index.tsx"),
  output: {
    path: path.join(__dirname, "dist"),
    filename: "bundle.min.js",
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.ts(x?)$/,
        exclude: /node_modules/,
        use: "ts-loader",
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

  • Build the widget using "npm run build".
  • Include the bundle.min.js file in your static HTML.
  • Open the static page in a browser and the React widget should display the random number passed from the static page.

Image description


Conclusion

Passing variables from static pages to widgets is essential for building flexible, dynamic, and modular components. By following the outlined steps, developers can ensure that their widgets integrate seamlessly into any environment while remaining secure and efficient. Widgets are a cornerstone of modern web development. With a little planning and care, they can be built to adapt to any context dynamically and securely.

widget Article's
30 articles in total
Favicon
Forex Ticker Widget: Simplifying Forex Monitoring for Users
Favicon
Passing variables from the static page to the widget
Favicon
How to launch a React Native app from the Lock Screen on iPhone
Favicon
Free Currency HTML-Widgets
Favicon
Integrating Live Forex Quotes into Your Trading Platform Seamlessly
Favicon
Implement a Secure, Dynamic Domain Approval System for Embeddable Widgets in Ruby on Rails
Favicon
The Future of Professional Networking on LinkedIn: How Businesses Can Adapt and Stay Ahead
Favicon
Embed JS Widgets with Rails: A Step-by-Step Guide
Favicon
Create embeddable widgets in react for static pages
Favicon
FloatyNavBar: Elevate Your Flutter App's Navigation
Favicon
Web music player with html-css-javascript
Favicon
Free Currency HTML-Widgets
Favicon
Building an embeddable Widget
Favicon
Video, Live Chat & Help Center widget for the website
Favicon
100 Common Flutter widget list
Favicon
Back to basic : Flutter widget lifecycle
Favicon
FlutterFlow has introduced this fantastic new draggable widget!
Favicon
Bigcommerce Widget Migration
Favicon
Simple Digital Clock Widget
Favicon
Exploring Simple Widgets II: Autocomplete
Favicon
Improved Data Point Graph Widget for Cumulocity IoT
Favicon
Enhancing Cumulocity IoT Capabilities: Map-Based Widgets
Favicon
The Journey of a Widget: Understanding the Lifecycle in Flutter
Favicon
flutter row widget example
Favicon
Flutter Column Widget Example
Favicon
Common Widgets in Flutter
Favicon
Creating an iOS Currency Exchange Rate Widget: A Step-by-Step Guide
Favicon
Flutter Custom Widget
Favicon
How to embed appointment scheduling widget on your website?
Favicon
How to screenshot a widget in the flutter

Featured ones: