Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 243
Van Minh Nhon TRUONG Avatar asked Mar 13 '26 22:03

Van Minh Nhon TRUONG


2 Answers

You don't need to create a separate function to handle onChange event

const checkboxref = useRef(null);

You can simply get the current value of the checkbox with:

checkboxref.current.checked 
// which returns a boolean
like image 63
William Mutua Peter Avatar answered Mar 16 '26 12:03

William Mutua Peter


use this one it might help you. here I am using createRef instead of useRef and also uses the callback hook which ensures the availability of ref when you click the button.

import React,{createRef, useCallback} from 'react';


export const HelloWorld = () => {
  const checkboxref = createRef();

  const handleOnClick = useCallback(() => {
    const node = checkboxref.current;
    if(node){
     node.focus();
     node.select();
     }
  }, [checkboxref]);

  return (
    <div>
      <button onClick={handleOnClick}>Focus</button>
      <input type="checkbox" ref={checkboxref} />
    </div>
  );
};
like image 26
DilipCoder Avatar answered Mar 16 '26 12:03

DilipCoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!