The functionality of onClick or onChange seems to be malfunctioning in the preline user interface select component

I recently integrated the preline UI library into my React project to enhance the design of my website. However, I encountered an issue where using the "select" element with the data-hs-select attribute as suggested by preline UI seemed to cause problems with onChange and onClick events. Strangely, nothing was triggered in the console when these events were fired. Despite this, the selected value was displayed correctly on the browser interface. Interestingly, I was able to retrieve the selected value using useRef or document selector methods.

Even after attempting to solve the issue by using formik field [as='select'], the problem persisted.

<select
      name='Country'
      data-hs-select='{
        "hasSearch": true,
        "searchPlaceholder": "Search...",
        "searchClasses": ...
      }'
      className='hidden'
      onChange={() => console.log('option clicked')}
    >
      <option value=''>Choose</option>
      <option value='Australia'>Australia</option>
      <option value='Canada'>Canada</option>
      <option value='France'>France</option>
      <option value='Germany'>Germany</option>
      <option value='Italy'>Italy</option>
    </select>

Answer №1

The onChange event is documented in the official Preline documentation.

For more information, visit Preline Docs

Answer №2

When navigating through inspect mode, the actual options remain hidden while the visible options in the UI are generated div elements with tailwind CSS classes. This causes the onChange method to not be triggered when changing the options.

After exploring a simple solution, here are the steps I discovered:

In your "select" component file,

  1. Add an "id" attribute to the select tag

    <select id='selectId' ... > //your options... </ select>

  2. Ensure to include the HSSelect class at the beginning of the file as well.

    import { HSSelect } from "preline/preline"

  3. Create a useEffect function:

useEffect(() => {
  const loadPreline = async() => {
    const { HSSelect } = (await import("preline/preline"))
    const el = HSSelect.getInstance("#selectId") as HSSelect
    el.on("change", (value: string) => {
      console.log(value)
    })
  }
  loadPreline()
  
}, [])  

Remember to import HSSelect within the loadPreline function. Since this is client-side code, dynamic importing is crucial for proper execution.

When obtaining the instance using HSSelect.getInstance("#selectId") as HSSelect, be sure to explicitly assign it to the HSSelect class from the package "preline/preline". Failure to do so may result in unexpected behavior.

Although it's a belated discovery, I trust this information will prove valuable in future endeavors. Thank you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger a React function once the user has finished typing

Is there a way to trigger a function (like querying a search service) only when the user stops typing or hits enter? I came across some examples that use lodash Debounce for this purpose. Currently, I'm experimenting with react hooks and wondering if ...

Restarting a timer with React useEffect

I've been experimenting with the useEffect hook and encountered a problem that has me stumped. My simple counter example uses setTimeout inside useEffect to update values. if (countState.stopWatch === 0) { dispatch({ type: 'reset' }); ...

The .find() function conveniently jumps over the table directly following its parent element

After clicking on Inner Add Row, the correct row is added from the .charts-series table. However, when I click on Outer Add Row, a row from the .charts-series table is added instead of one from the .charts table. Here is the link to the example: http://jsf ...

What strategies can I use to prevent any spaces between cards when I unfold them?

Hello, I am looking to create a basic webpage. In this link, there are 4 cards that can be opened. However, when I open card B, a gap appears between card A and card C - and I'm not sure why this is happening. Here is a link to the HTML code I have us ...

Styling tables within HTML emails for Gmail and then utilizing PHPMailer to send the emails

I've been racking my brain over this for hours with no luck! Objective: Implementing inline styles for table, td, th, p elements in an HTML email intended for Gmail using PHPMailer. Challenge: Inline styles not being rendered HTML Snippet: <sec ...

Returning a 'never' type from a function in React using Typescript

Basically, I have a function that initiates the OAuth flow (redirecting to Google OAuth login page, for example): async function signIn() { // start OAuth flow } And let's say I want to use it in a useEffect hook like this: ... useEffect(() => { ...

Having trouble establishing a connection to the back-end server with minikube

I am currently facing an issue with deploying an application in minikube locally. While I can successfully connect to the front-end when minikube is running, I encounter connectivity problems with the back end. Below are the yaml files that I am using: I ...

Having trouble importing my function component into a router in reactjs. Need some guidance on how to properly set it up

I am working on a Slider component function called export default Slider. In my App.js file, I have the following code: function App() { return ( <Router> <Routes> <Route exact path='/' element={<Home />} /> ...

The AppBar component is designed to display the title property of its child component

Within my app setup, I am facing the following issue: <App> <DynamicView /> </App> The goal is for App to display the title property of its child component DynamicView. The attempt made was: <h1>{children[0].props.title}</h1 ...

Creating a static CSS lightbox with scrolling content

I am trying to create a CSS lightbox for an image gallery, where the images displayed in the lightbox need to be large so their content is easily readable. The lightbox container is fixed in its position, but I require the images to be scrollable along the ...

Troubleshooting issues with jQuery background-position animation and CSS sprites functionality

Trying to add animation to my navigation links background using a Css sprite. Check out the picture here: $(document).ready(function(){ $('nav a') // Move the background on hover .mouseover(function(){ $(this).stop().animate({ba ...

Using HTML5 Canvas: Implementing an Image.onload() function through Image.prototype

I am trying to create a simple function that will refresh the canvas automatically when an image is loaded. The idea is to be able to use code like this: var map = new Image(); map.onloadDraw(); map.src = "images/" + worldmapCanvasShapeImage; Currently, ...

How can I incorporate dynamic moving lines into my website's loading sequence?

Link to Gyazo image 1: https://gyazo.com/015425f0decb187e28b620c1e3206391 Issue with first image: https://gyazo.com/dfcd33e8a4fd5bea64e51fe40556f0bf I'm currently working on a website and came up with a cool concept of having two lines crossing the s ...

What prevents Django websites from being embedded within another HTML (iframe)?

I attempted to include a Django form within another HTML page, but it's not functioning correctly. I've tried on several of my other Django sites with no success. I even tested it on other websites as well. Is there a restriction on using Django ...

What is the method for customizing the scroll highlight color within bookdown by modifying the style.css file?

One interesting aspect of Bookdown is its built-in feature that automatically highlights in blue the section in the sidebar that you are currently scrolling past or reading. However, I'm having trouble changing the color in the style.css page. Using a ...

Issues arise with the behavior of Bootstrap design when adapting to different screen sizes, as well as

I am currently working on designing my personal portfolio using Bootstrap. I have made some progress with the setup, but I am encountering some issues. When I resize the window, the top menu collapses into a button. However, when I click on the button, n ...

Using this.setState in ReactJS removes filters

Hey everyone, I've been struggling with a technical issue for the past few days and would really appreciate any hints or solutions. The problem lies in creating a table using the material-table library. Specifically, I need to extract the docID and do ...

I require a breakdown of the JavaScript code, please

Are you struggling with a code snippet that involves CSS, JavaScript, and HTML? Let's take a look at the complete code: <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="http://snipplicious.com/css/bo ...

Transform an array of strings into an array of floating point numbers using AngularJS

Hey everyone! I'm having trouble converting an array of strings into floats. When using map(parseFloat), I'm only getting integer numbers. Could the issue be with the commas in 40,78 causing parseFloat to interpret it as 40 instead of 40.78? Her ...

AngularJS fetches the 'compiled HTML'

If I have this angularjs DOM structure <div ng-init="isRed = true" ng-class="{'red': isRed == true, 'black': isRed == false}"> ... content </div> How can I obtain the 'compiled' version of this on a cl ...