简体   繁体   中英

Trigger child onchange handler from click on parent element with React

I want to expand the clickable area of a Select component I have that I don't have access to change it (comes from a lib).

This Select component is wrapped by a div... I thought about adding a click handler to this div so that when a user clicks on it, it triggers the click on the Select. It would do it, if the select also had an onClick handler, but instead, of course, it has an onChange, which is not triggered.

I wanted help to find a proper way to trigger it.

This is a simplified version of my JSX code:

<div data-testid="language-select">
  <MyCustomSelect
    id="language-selector"
    options={languageList.map(({ locale, title }) => ({
      value: locale,
      children: title,
    }))}
    value={currentLocale}
    onChange={({ target: { value } }): void => {
      global.location.replace(resolveUrl(value));
    }}
  />
</div>;

What I did:

Added onClick to div:

onClick={() => {
  const languageSelector = document.getElementById('language-selector');
  languageSelector?.click();
}}

But then as I said it doesn't work as it doesn't trigger the change.

Is there a proper way to achieve this behavior?

EDIT: I created this sandbox to help understanding my issue: https://codesandbox.io/s/adoring-wildflower-0ido5j?file=/src/App.js:561-569

So I want to find a way to click on the red part (the div), and fire the select.

You can use ref to access child component methods, but it should let you do click event

<div data-testid="language-select">
  <MyCustomSelect
    id="language-selector"
    options={languageList.map(({ locale, title }) => ({
      value: locale,
      children: title,
    }))}
    value={currentLocale}
    onChange={({ target: { value } }): void => {
      global.location.replace(resolveUrl(value));
    }}
   ref={ref} // Pass ref
  />
</div>

Div click

ref.current.onClick

It will be good if you can share a library which your are using or a working demo for the issue

you could try referencing the select

like:

  import React, { useRef } from 'react';
  .
  .
  .
  const SelectRef = useRef(null)
  render (
    <div onClick={()=> SelectRef.current.click()}>
      <MyCustomSelect
        id="language-selector"
        ref={SelectRef}
        options={languageList.map(({ locale, title }) => ({
          value: locale,
          children: title,
        }))}
        value={currentLocale}
        onChange={({ target: { value } }): void => {
          global.location.replace(resolveUrl(value));
        }}
      />
    </div>
  )

It may not work, can you let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM