retrieve category clicked and send data by post method using ajax to update a gallery

I’m using WordPress, and I’m trying to learn how to create a filterable gallery on my own using ajax. To achieve this, I’ve created a page with a template called filterable-gallery-template.php. The file is located in my child theme. In my page, I’ve added a JavaScript snippet using wpcode and calling it with a shortcode.

What I’m attempting to do is to obtain the category value when a button is clicked, send this value to my PHP template, and then filter my gallery (I’ve added categories for my images using a plugin). However, I’m facing a 500 error. I’ve tried to retrieve the value of var_dump($category), and I have succeeded in getting the category name only once when visiting the page for the first time. After that, the buttons don’t work, and I don’t see any images. Here is my code, thanks in advance for your help 🙂

filterable-gallery-template.php

`<?php
/* Template Name: filterable Gallery */
?>

<nav class="filterable-gallery">
    <ul>
        <li><a class="wp-block-button__link filterable-gallery__btn on">Print</a></li>
        <li><a class="wp-block-button__link filterable-gallery__btn">Webdesign</a></li>
        <li><a class="wp-block-button__link filterable-gallery__btn">Branding</a></li>
        <li><a class="wp-block-button__link filterable-gallery__btn">Illustration</a></li>
    </ul>
</nav>

<div class="gallery">
    <?php
    
   $category = isset($_POST['category']) ? $_POST['category'] : 'Print';
    
    
    echo '<pre>';
    var_dump($category);
    echo '</pre>';
    
    $args = array(
        'numberposts'    => -1,
        'orderby'        => 'menu_order',
        'order'          => 'ASC',
        'post_mime_type' => 'image',
        'post_parent'    => get_the_ID(),
        'post_status'    => null,
        'post_type'      => 'attachment',
        'tax_query'      => array(
            array(
                'taxonomy' => 'attachment_tag',
                'field'    => 'slug',
                'terms'    => $category,
            ),
        ),
    );

    $images = get_posts($args);

    if ($images) {
        foreach ($images as $image) {
            $image_id = $image->ID;
            $title = get_the_title($image_id);
            ?>
            <div class="gallery-item">
                <img src="<?php echo wp_get_attachment_url($image_id); ?>" alt=""/>
                <div class="overlay">
                    <h5><?php echo $title; ?></h5>
                </div>
            </div>
            <?php
        }
    } else {
        echo '<p>Aucune image trouvée avec la catégorie "' . esc_html($category) . '".</p>';
    }
    ?>
</div>
`

Javascript snippet

`jQuery(document).ready(function($) {
    let isActive = document.getElementsByClassName('on');
    let buttons = document.getElementsByClassName('filterable-gallery__btn');

    for (let buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
        buttons[buttonIndex].addEventListener('click', function(event) {
            activer(event);
        });
    }

    function activer(e) {
        let categoryClicked = null;

        if (!e.target.classList.contains('on')) {
            for (let i = 0; i < isActive.length; i++) {
                isActive[i].classList.remove('on');
            }
            e.target.classList.add('on');
            categoryClicked = e.target.innerText.toLowerCase();
        } else {
            return;
        }
        console.log(categoryClicked);
        // Utilisation de jQuery pour simplifier la requête AJAX
        $.ajax({
            type: 'POST',
            url: '/wp-content/themes/twentytwentyone-child/filterable-gallery-template.php',
            dataType: 'html',
            data: {category: categoryClicked },
            success: function(response) {
                console.log(response);
            },
        });
    }
});
`

How do I make an infinite while loop in JavaScript?

So I wanted to make a simple effect of snowflakes falling from the sky randomly. I can make them all fall at the same time with different velocities, but i cant seem to call for a while loop again only for +1 snowflake. Here is the link for the whole thing to give u an idea of what it should look like

Here is the code:

function createSnowflakes() {
    let i = 0;
    while (i < 30) {
        document.body.innerHTML += `<div  class="snowflake${Math.floor(Math.random()*10)} snowflakes"></div>`;
        i++
    }
    let snowflakes = document.querySelectorAll('.snowflakes');

    snowflakes.forEach((snowflake) => {
        snowflake.style.transform = `translateX(${window.innerWidth * Math.random()}px)`;
        snowflake.style.animation = `falling1 ${Math.floor(Math.random() * 8)+3}s linear forwards`;
    })

    snowflakes.forEach((elem) => console.log(elem));
    snowflakes.forEach((elem) => {
        elem.addEventListener('animationend', e => {
            elem.remove();
            snowflakes = document.querySelectorAll('.snowflakes');
            if (snowflakes.length < 10) {
                createSnowflakes();
            }
        })
        
    })
}

createSnowflakes();

Using Velo api in wix to update product image

Im tring to use the docs of velo, to remove from product image by selecting it from gallery.
the officel docs is
export function removeProductMedia(productId, media) { return wixStoresBackend.removeProductMedia(productId, media); }

but it donsent work, it seems that the problem have connection to “media” parametr in the function.

i try evrithing. and im alredy using function with the same syntaxt and with the same parameter that work
export function addProductMedia(product, mediaData) { return wixStoresBackend.addProductMedia(product, mediaData); }

you guys have any idea?

that my first time asking in stackoverflow after years of using

im passing for trying tamplate image
and the result “src.tolocalelowercase is not a function”
{ "description": "", "id": "c3904a_3efe2c7fd11d480199986dd13ead530a~mv2.jpg", "link": "null", "src": "wix:image://v1/c3904a_3efe2c7fd11d480199986dd13ead530a~mv2.jpg/file.jpg#originWidth=720&originHeight=1600", "title": "", "type": "Image" }

how to use useEffect to set a state but also prevent the infinite re-render?

I have a state as below:

const [doctor, setDoctor] = useState<doctorStateProps | null>(null)

and then a useEffect function as follows:

useEffect(() => {
        if(!doctor){
            axios.get(`doctor/${id}`).then(({data}) => {
                setDoctor(data)
            })
        }
    }, [doctor])

I also have this function to enable the user to rate a doctor:

   const handleReview = async () => {
        try {
            if(text === '' || rating === 0){
                errorNotification('field cannot be empty')
            }else {
                await axios.post(`/doctor/${id}/review`, {text, rating, createdAt: moment(dayjs(date).toDate()).format('LL') })
                setText('')
                setRating(0)
                setGiveReview(false)
                setDoctor(null)
                successfulNotification('feedback received')
            }
        } catch (error) {
            errorNotification('error, please try again later')
        }
    }

The plan is for axios to get the doctor everytime a user refreshes the page, but i also want the doctor page to automatically update the doctor’s average rating when the user rates a doctor. However, the code above causes an infinite loop of re-renders.

I know this is not the ideal way of doing this but i cant figure out how to do it while simultaneously preventing the re-rendering. How do i go about this?

How do I display the placeholder for the phone number using intl-tel-input

I’m trying to display the formatted country code in the input placeholder, but it only shows the country code

                     <input type="tel" name="celular" class="form-control input-telefone" placeholder="<?php echo site_phrase('celular'); ?>" aria-label="<?php echo site_phrase('celular'); ?>" aria-describedby="selected-country-code" id="celular" required style="border-top-left-radius: 0px;padding-left: 60px;border-bottom-left-radius: 0px;">

I have tried using the formatNumber and getNumber methods, but none of them returns the example number; only the getNumber method returns ‘-99’ for all selected countries.

$(document).ready(function () {
  const input = document.getElementById("celular"); // Usando document.getElementById em vez de $("#celular")
  const iti = intlTelInput(input, {
    initialCountry: "br",
    placeholderNumberType: "MOBILE",
    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/utils.js",
  });

   input.addEventListener("countrychange", function (event) {
        const countryData = iti.getSelectedCountryData();
        const numberType = iti.getNumberType();

        input.placeholder = "+" + countryData.dialCode + " " + iti.getNumberType();
        $("#selected-country-code").text("+" + countryData.dialCode);
    });

    input.addEventListener("input", function (event) {
        // Realize qualquer formatação adicional, se necessário
    });
});
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/css/intlTelInput.min.css">

  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/intlTelInput-jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/utils.js"></script>

How to display in the placeholder

How to import tradingview library in flutter web-view

I am trying to import tradingview charting library into flutter webview on iOS.

I am using webview_flutter: ^4.4.4 and below is the code

<!DOCTYPE html>
<html lang="en">
<head>

    <title>TradingView Advanced Charts demo -- Mobile (black)</title>

    <!-- Fix for iOS Safari zooming bug -->
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0" name="viewport">

    <script src="charting_library/charting_library.standalone.js"
            type="text/javascript">
    </script>
    <script src="datafeeds/udf/dist/bundle.js" type="text/javascript">
    </script>

    <script type="text/javascript">
        function initOnReady(to, from) {
            var datafeedUrl = "http://127.0.0.1:8000";
            // ConsoleLog.postMessage("check1234");
            var scripts = document.getElementsByTagName('script');
            Array.from(scripts).forEach(script => ConsoleLog.postMessage("script -> " + script.src));
            // var datafeedUrl = "https://demo-feed-data.tradingview.com";
            // var from = 1531009291;
            // var to = 1541009291;
            var widget = window.tvWidget = new TradingView.widget({
                symbol: 'AAPL',
                interval: '1D',
                container: "tv_chart_container",
                //  BEWARE: no trailing slash is expected in feed URL
                datafeed: new Datafeeds.UDFCompatibleDatafeed(datafeedUrl, undefined, {
                    maxResponseLength: 1000,
                    expectedOrder: 'latestFirst',
                }),
                library_path: "charting_library/",
                locale: "en",
                time_frames: [
                    {text: "1y", resolution: "1D", description: "1 Year"},
                    {text: "3m", resolution: "1D", description: "3 Months"},
                    {text: "1m", resolution: "1D", description: "1 Month"},
                    {text: "1w", resolution: "60", description: "1 Week"},
                    {text: "1d", resolution: "5", description: "1 Day"},
                    {text: "1000y", resolution: "1D", description: "All", title: "All"}
                ],
                timeframe: {"to": to, "from": from},

                disabled_features: [
                    'use_localstorage_for_settings',
                    'left_toolbar', 'header_widget', 'timeframes_toolbar', 'edit_buttons_in_legend', 'context_menus', 'control_bar', 'border_around_the_chart',
                ],
                overrides: {
                    "paneProperties.background": "#222222",
                    "paneProperties.vertGridProperties.color": "#454545",
                    "paneProperties.horzGridProperties.color": "#454545",
                    "scalesProperties.textColor": "#AAA"
                },
                debug: true,
                onReady: function (api) {
                    api.setVisibleRange({
                        from: from / 1000,
                        to: to / 1000
                    });
                }
            });
        }
    </script>

</head>

<body style="margin:0px;">
<div id="tv_chart_container"></div>
</body>

</html>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

class TradingViewWidgetChart extends StatelessWidget {
  const TradingViewWidgetChart({
    required this.height,
    required this.width,
    required this.assetName,
    required this.toTime,
    super.key,
  });

  final double height;
  final double width;
  final String assetName;
  final int toTime;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: height,
      width: width,
      color: Colors.greenAccent,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: TradingViewCompactChartWidgetHtml(
            assetName: assetName, toTime: toTime, fromTime: toTime - 1000000),
      ),
    );
  }
}

class TradingViewCompactChartWidgetHtml extends StatefulWidget {
  const TradingViewCompactChartWidgetHtml({
    required this.assetName,
    required this.toTime,
    required this.fromTime,
    super.key,
  });

  final String assetName;
  final int toTime;
  final int fromTime;

  @override
  State<TradingViewCompactChartWidgetHtml> createState() =>
      _TradingViewCompactChartWidgetHtmlState();
}

class _TradingViewCompactChartWidgetHtmlState
    extends State<TradingViewCompactChartWidgetHtml> {
  late final WebViewController controller; // Declare as nullable

  @override
  void initState() {
    super.initState();
    controller = WebViewController() // Initialize the controller here.
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..addJavaScriptChannel(
        'ConsoleLog',
        onMessageReceived: (JavaScriptMessage message) {
          print("JS Console: ${message.message}");
        },
      )
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            debugPrint('progress$progress');
          },
          onPageStarted: (String url) {
            debugPrint('started');
          },
          onPageFinished: (String url) {
            debugPrint('finished: $url');
            Future.delayed(Duration(milliseconds: 5000), () {
              debugPrint('hello world');
              controller.runJavaScript("""
        initOnReady(${widget.toTime}, ${widget.fromTime});
            """);
              debugPrint('hello world');
            });
          },
        ),
      )
      ..enableZoom(true)
      ..loadFlutterAsset('js_scripts/advanced.html');
  }

  @override
  Widget build(BuildContext context) {
    // return
    return WebViewWidget(controller: controller);
  }
}

What I expect:
Tradingview charting library (standalone) and datafeeds/udf/dist/bundle.js gets imported at loadFlutterAsset and when page load gets finished, I pass the initOnReady function, the required params to load the Tradingview chart

What is happening:
I am getting the following error

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., A JavaScript exception occurred (WKErrorDomain:4:{WKJavaScriptExceptionLineNumber: Unsupported Type: 25, WKJavaScriptExceptionMessage: ReferenceError: Can't find variable: TradingView, WKJavaScriptExceptionSourceURL: Unsupported Type: file:///Users/username/Library/Developer/CoreSimulator/Devices/12E3ECA1-FD47-4B49-9F22-7B5B0147E8F4/data/Containers/Bundle/Application/8692A5E5-A6C1-4799-A20C-22CCC4C8F012/Runner.app/Frameworks/App.framework/flutter_assets/js_scripts/advanced.html, NSLocalizedDescription: A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber: Unsupported Type: 59}), null)
#0      WKWebViewHostApiImpl.evaluateJavaScriptForInstances (package:webview_flutter_wkwebview/src/web_kit/web_kit_api_impls.dart:1082:7)
<asynchronous suspension>
#1      WebKitWebViewController.runJavaScript (package:webview_flutter_wkwebview/src/webkit_webview_contro<…>

What I have checked?

Using

var scripts = document.getElementsByTagName('script');
            Array.from(scripts).forEach(script => ConsoleLog.postMessage("script -> " + script.src));

I can see that the library is getting imported at

flutter: JS Console: script -> file:///Users/username/Library/Developer/CoreSimulator/Devices/12E3ECA1-FD47-4B49-9F22-7B5B0147E8F4/data/Containers/Bundle/Application/8692A5E5-A6C1-4799-A20C-22CCC4C8F012/Runner.app/Frameworks/App.framework/flutter_assets/js_scripts/charting_library/charting_library.standalone.js
flutter: JS Console: script -> file:///Users/username/Library/Developer/CoreSimulator/Devices/12E3ECA1-FD47-4B49-9F22-7B5B0147E8F4/data/Containers/Bundle/Application/8692A5E5-A6C1-4799-A20C-22CCC4C8F012/Runner.app/Frameworks/App.framework/flutter_assets/js_scripts/datafeeds/udf/dist/bundle.js

but the application still throws error saying Can't find variable: TradingView which is present in the standalone library.

I would appreciate any help. I have tried adding logs and other things but am not able to come to solution. Thankyou

CreatePortalLink doesn’t point to a dashboard but a payment url

I have a project which uses the Stripe payments extension with Firebase. The app runs with Next JS.

Once the user is subscribed, I need a tab for them to manage their subscription. The extension tells you to run their cloud function, createPortalLink. Here is my implementation of it:
const functions = getFunctions(getApp())
const functionRef = httpsCallable(functions, “ext-firestore-stripe-payments-createPortalLink”)

    const {data} = await functionRef({
        returnUrl: window.location.href + "/plans",
        locale: "auto",
    })
    
    // @ts-ignore
    window.location.assign(data.url)

When I run this, it just goes to a payment page and not a dashboard which could allow you to manage, and most importantly, delete subscriptions.

Is there something I need to change or does it just work like this in test mode?

Nextjs Hydration issues. Deleting page-cache in order to avoid hydration issues

I noticed that everytime I make changes in my code, I would have to empty my page-cache in order to avoid hydration issues. Is there a way to avoid this?

I’m creating this simple Navbar for example

import Link from "next/link";


const Navbar = () => {

    return (
        <div className="w-full h-20 bg-indigo-800 sticky top-0">
            <div className="container mx-auto px-4 h-full">
                <div className="flex justify-center items-center h-full text-2xl">
                    <div className="flex flex-row gap-x-6 text-white">

                        <Link href="/" >Home</Link>

                        <Link href="/login">Login</Link>

                        <Link href="/signup">Sign-up</Link>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Navbar;

I don’t really want to keep deleting my page-cache unless that’s how it goes? but i don’t think so.

Texture not loading 100% of them time with THREE.JS

I am trying add a texture to a 3d object and eventually be able to scale it on the 3D object as well. But the texture only loads in maybe 5% of the time, the rest of the time the 3D object has no textures.

I was expecting the texture to load 100% of the time and then I could play around with other variables to change scale, rotation ect.


import * as THREE from "https://cdn.skypack.dev/[email protected]/build/three.module.js";
import { OrbitControls } from "https://cdn.skypack.dev/[email protected]/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from "https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 1000);

let object;
let controls;

let objToRender = 'shorts';

const loader = new GLTFLoader();

loader.load(
  `models/${objToRender}/scene.gltf`,
  function (gltf) {
    object = gltf.scene;
    scene.add(object);

    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    
    const image = new Image();
    image.onload = function() {
        canvas.width = image.width;
        canvas.height = image.height;
        context.drawImage(image, 1, 1);
        
        const canvasTexture = new THREE.CanvasTexture(canvas);
        object.getObjectByName('shorts1').material.map = canvasTexture;
        object.getObjectByName('shorts2').material.map = canvasTexture;
    
        canvasTexture.needsUpdate = true;
    };
    image.src = 'textures/smile.png';
  },
  function (xhr) {
    console.log((xhr.loaded / xhr.total * 100) + '% loaded');
    
  },
  function (error) {
    console.error(error);
  }
);

const renderer = new THREE.WebGLRenderer({ alpha: true }); 
renderer.setSize(window.innerWidth, window.innerHeight);

document.getElementById("container3D").appendChild(renderer.domElement);

camera.position.z = objToRender === "shorts" ? 25 : 500;

const topLight = new THREE.DirectionalLight(0xffffff, 1); 
topLight.position.set(500, 500, 500); 
topLight.castShadow = true;
scene.add(topLight);

const backLight = new THREE.DirectionalLight(0xffffff, 1); 
backLight.position.set(-500, -500, -500);
backLight.castShadow = true;
scene.add(backLight);

const ambientLight = new THREE.AmbientLight(0x333333, objToRender === "shorts" ? 2 : 1);
scene.add(ambientLight);

if (objToRender === "shorts") {
  controls = new OrbitControls(camera, renderer.domElement);
}

function animate() {
  requestAnimationFrame(animate);

  renderer.render(scene, camera);
}

window.addEventListener("resize", function () {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

animate();

Data structures in JS [closed]

This is more of a conceptual doubt than a hands on doubt. I was trying to boost my strength in DSA when I go this doubt. In Javascript there are not all types of data structures. For example, linked lists do not have an in built class. So if I want to implement a LL in JS should I create a custom class for it every time? I can create a class and access the methods of the class. But what is the point of it? Instead I can write similar logic of the class’ methods in a custom function and use that with arrays itself. So to put clearly here are the questions:

  1. Why can’t I create the functionality of these other data structure methods as custom functions and use it with arrays?
  2. How do I implement those DS that do not have JS in built classes?
  3. What is the best source to learn how to implement different data structures in JS? Is there any other way that to just create class and instantiate? And if no, why should I do it?

I was unable to find the exact answers for these questions. Please let me know.

Getting users to join a group but subject to approval of the group owner in PHP

I have user and group tables in db. Users can create groups. Other registered users can see all the groups from their dashboards and to join any group of their choice. But I want group owners to be able to see all the users that want to join their groups to accept or decline the applications.

Also the joiners should be able to see the status of their application if pending, approved or decline.

I need some guides on how to implement this in PHP.

Many thanks

Benny

How to fix CORS when request is coming from Chrome Extension?

I am writing a Chrome Extension that needs to make a call to my server. I am getting

Access to fetch at (server-website) from origin ‘chrome-extension://abc’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled

However I have my express js server setup to handle CORS from the chrome extension

var cors = require("cors");
var corsOptions = {
  origin: [
    "server-url",
    "chrome-extension://abc",
  ],
};
app.use(cors(corsOptions), express.static(path.join(__dirname, "public")));

What am I doing wrong here?

Tailwind CSS Completely remove Light Mode

I downloaded a Tailwind CSS template online, hoping to streamline the process of a project I was working on, and I ran into a little problem; I can’t get rid of light mode. There is a settings toggle, where you can either toggle dark mode or off. Problem is, dark mode doesn’t stick when you reload, or change to another page. Here is the Javascript of the toggle:

  const lightThemeButton = document.querySelector('.lightThemeButton')
  const darkThemeButton = document.querySelector('.darkThemeButton')
  const logo = document.querySelector('.navbar-logo img')

  darkThemeButton.addEventListener('click', () => {
    document.body.classList.add('darkTheme')
    sidebarNavWrapper.classList.remove('style-2')
    darkThemeButton.classList.add('active')
    lightThemeButton.classList.remove('active')
    logo.src = 'assets/images/logo/logo-white.svg'
  })

  lightThemeButton.addEventListener('click', () => {
    document.body.classList.remove('darkTheme')
    sidebarNavWrapper.classList.remove('style-2')
    lightThemeButton.classList.add('active')
    darkThemeButton.classList.remove('active')
    logo.src = 'assets/images/logo/logo.svg'
  })

Here is the SCSS of the toggle:

.darkTheme {
  color: rgba($white, 0.7);

  .text-gray {
    color: rgba($white, 0.5) !important;
  }

  .card-style {
    box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.2);

    .dropdown-menu {
      background: $dark-2;
    }
  }

  .more-btn-wrapper {
    .dropdown-menu {
      border-color: $dark-4;

      .dropdown-item {
        a {
          color: $white;
        }
      }
    }
  }
}

How would I go about completely deleting light mode? As far as I’m concerned, I can’t find a single page in the SCSS given that relates to the light mode, and there’s hundreds of files in the CSS category so there’s got to be a more efficient way than editing each one. If that’s not possible, how would I get it to stay that way upon reload, or better yet: Default to dark mode upon page load?

I’ve tried everything in Tailwind’s documentation relating to dark mode. Setting up the config file and putting class="dark" in the body/html tags do not work.

Disable plugin in react-chartjs2?

I’m trying to dynamically enable and disable plugins rendered a react-chartjs-2 component.

The plugins that should be rendered are passed to the component like this:

import { useRef, useEffect } from 'react';
import { my_plugin_t} from '../types/all_types'
import { Chart as ChartJS, ChartType,  registerables, ChartOptions } from 'chart.js';
import { Line } from 'react-chartjs-2';

const MyPlot = ({signals, plugin_list}: { signals: signal_t[], plugin_list: any[]}) => {

    ChartJS.register(...registerables);
    // ... chart setup of data and options...
   
    return(
        <>
        <Line ref={chartRef} data={data} options={options} plugins={plugin_list} />
        </>
    )
}

When the plugin_list includes the plugins that need to be drawn in the first rendering of the component it shows up fine. When I leave it empty, it does not show up.
However, changing plugin_list does not toggle whether the plugin is enabled or disabled.

Is there a way to dynamically add or remove plugins to the Line component?

React/NextJs – How to get Snap-Scroll Position?

My Demo | Source Code

I have a “Question Container” with the CSS (Tailwind) Properties :
snap-y snap-mandatory overflow-auto
and inside that “Question Container” there live 4 dynamically rendered “Question”s with Properties
snap-center 100% Height/Width.
Like Screens you scroll down to the next question.

Now the problem is that i have no clue how i can read on which Question i am and then of course how to scroll to the next/previous when i’m clicking on that “ArrowUp” “ArrowDown” Button or the “OK” Button.

Window.scrollBy doesnt work either because obviously it lives in a container that is scrollable.

And i additionaly i want to prevent scrolling before a answer is selected.

Can anyone help me what i need to add in the project to make it working ?
Then i can continue doing the rest of the logic by myself

I did try Googleing and asking on Reddit, Gutefrage.net, ChatGPT.
Result => No Similar Case Found and got no Help on other Forums.

I expect maybe a little Code Snippet what i need to add or ideal a github pull request from a more expierenced User.