How to programmatically focus a button in React?
Asked Answered
M

1

6

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?

Mahout answered 26/4, 2022 at 20:4 Comment(0)
F
5

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

Faun answered 26/4, 2022 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.