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

Improving List performance with React.cloneElement

I am uncertain about the usage of React.cloneElement within a List component. Is it recommended to avoid using it, especially when dealing with a large number of elements in the list? Does React.cloneElement cause unnecessary re-renders that can be optimal ...

I am encountering difficulties accessing the cPanel URL following deployment on Vercel

Running into some challenges while hosting my Next.js 13 application on cPanel led me to an alternative solution I discovered online. The workaround involved deploying the application on Vercel and adjusting the DNS records in cPanel to direct traffic to ...

Every time I attempt to run the npx command, I encounter an error that says: "Error: EPERM: operation not permitted

Struggling to install the create-guten-block package using the command npx create-guten-block my-block, but unfortunately, it's not working out for me. My current node version is 10.15.1 Npm version I'm on is 6.4.1 Encountering the error shown ...

Steps for properly inserting a hyperlink:

I'm in need of assistance. I have a grid containing several images that I want to make clickable by adding anchor tags, but when I do this, the images seem to disappear completely. I suspect there's an issue with them being inside the container d ...

How can I transform an HTML element into a textarea using CSS or JavaScript?

While browsing a webpage, I discovered a <div> element with the class .plainMail and I want to find a way to easily select all its text by simply pressing Ctrl+A. Currently using Firefox 22, I am considering converting the div.plainMail into a texta ...

The Wonders of Flex Box and Media Queries

Can a website still be made responsive without relying on media queries when flexbox is already implemented? Are there specific scenarios where the utilization of media queries offers enhanced control? ...

Solving problems with accessing global variables in React Redux

I'm currently working on implementing a global state in react-redux for my project. However, I've encountered an issue with retrieving updated values after dispatching an action to populate the global state for the User. Below are snippets of the ...

What is the impact of a floated element on vertical spacing?

I have come across an article discussing the usage of CSS, but I am puzzled as to why image number four is not positioned below image number one. Instead, it appears below image number three. Can someone please explain this to me? Here is the HTML code sni ...

ReactJS encountered an issue while attempting to remove an item from the state

I've been encountering an issue while attempting to remove an item from state in React. Even though the API call successfully deletes the item (as confirmed through the browser inspector and page reload), the item remains visible until the user manual ...

When using React router, I'm experiencing a redirection issue where instead of being directed to the /login route,

I am currently developing a web application with an authentication system. I have encountered an issue when logging out. Instead of redirecting me to the /login page, it redirects me to /[object%20Object]. Can anyone help me figure out what might be causin ...

Locate the present position of the slider element

I am currently in the process of creating a website that features pages displayed in a slider format. Each page has its own unique ID, but all share a common class called 'section'. However, I am encountering difficulty in identifying the ID of t ...

Issue with React - Axios get request resulting in empty data response

I have encountered a Null pointer exception while making a get request from my back-end spring project. Despite the path being correct and returning the expected value during unit testing, an error occurs when calling via axios get. ERROR: trace: "ja ...

"Implementing state changes within a static function in React Native – a simple

Is it possible to use setState within a static function in React? I attempted to do so, but an error was returned stating that setState is not a function: export default class SearchTab extends React.Component { constructor(props) { ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

My custom Wordpress template experiences a hiccup with the jQuery slideshow, as it unexpectedly

Looking for help with a slideshow issue. Initially, it loads and transitions smoothly into one picture, but then stops working. I decided to use Chrome to troubleshoot the problem, and it informed me that it doesn't recognize the slideSwitch function ...

What is the best way to stop a select menu option from being highlighted once it has been clicked on?

Is there a way to prevent the highlighting of selected options in a <select> menu when a user makes a selection? <select id="my_select_menu"> <option id="1">Option 1</option> // I do not want this option to be highlighted ...

What is the best way to increase the spacing between inline-block elements?

Just to clarify, I am not looking to delete space between inline-block elements - rather, I want to insert it. My goal is to create a grid of menu items that can accommodate 2, 3, or 4 items per row, and I hope to achieve this using media queries. Is the ...

Styling with CSS to show an image and text on the same line

I would like to show text and image on the same line, with the image slightly above the text. View Demo html img.del { display: inline-block; float: right; cursor: pointer; margin-right: 74% } .astext { text-align: left; margin-le ...

Is extracting the primary image from a WordPress post using raw post data the ideal solution?

I am currently working on a website that needs to showcase the first image from each post in a specific category. Despite having a functioning solution in place, I can't help but feel like there might be a more efficient way to achieve this. Is there ...

JavaScript Issue Causing Jquery Carousel Dysfunction

I am having trouble with the slider I created using JS Fiddle. The link to the slider is not working and I need some assistance. Click here for the slider <div class="row"> <div id="myCarousel" class="carousel slide vertical"> &l ...