jeudi 25 février 2021

How to focus and select a checkbox using React ref?

I have been looking around a method to correctly focus and select a checkbox in React code. The methods focus() and select() that I'm using in the example below are not working :

import React, { useRef } from "react";

export const HelloWorld = () => {
  const checkboxref = useRef(null);

  const handleOnClick = () => {
    checkboxref.current.focus();
    checkboxref.current.select();
  };

  return (
    <div>
      <button onClick={handleOnClick}>Focus</button>
      <input type="checkbox" ref={checkboxref} />
    </div>
  );
};

When I click on the button, my checkbox is not focused and not selected...

Any solution please ?

Thank you so much.




Aucun commentaire:

Enregistrer un commentaire