Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to programmatically focus a button in React?

Autofocus does not work for me because I need it (button2) to focus when button1 gets clicked, not when the element loads. This is what my code looks like:

const MyComponent = props =>{

    return(<div>
                <button id='button1'>Button1</button>
                <button id='button2'>Button2</button>
           </div>);
}

I tried using a ref but it doesn’t seem to work on buttons, just textboxes and the like; when I replaced button2 with an <input> it worked fine:

const MyComponent = props =>{
    const btnRef = useRef()
    const handleClick = ()=>{
        btnRef.current.focus()
    }
    return(<div>
                <button id='button1' onClick={handleClick}>Button1</button>
                <button id='button2'>Button2</button>
           </div>);
}

Is there a way to make this ref approach work? Or just any way to make buttons focus programmatically?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are on the right track, you need to also attach the ref to the DOM element you want to call .focus on.

Example:

const MyComponent = () => {
  const btnRef = useRef();

  const handleClick = () => {
    btnRef.current.focus();
  };

  return (
    <div>
      <button id="button1" onClick={handleClick}>
        Button1
      </button>
      <button ref={btnRef} id="button2">
        Button2
      </button>
    </div>
  );
};

The issue seems that even though the button has browser focus there is no visual indication. You can provide this.

Example using styled-components:

const Button = styled.button`
  &:focus {
    outline: 2px solid red;
  }
`;

const MyComponent = () => {
  const btnRef = useRef();

  const handleClick = () => {
    btnRef.current.focus();
  };

  return (
    <div>
      <button id="button1" onClick={handleClick}>
        Button1
      </button>
      <Button ref={btnRef} id="button2">
        Button2
      </Button>
    </div>
  );
};

Edit how-to-programmatically-focus-a-button-in-react

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading