Home > OS >  How to programmatically focus a button in React?
How to programmatically focus a button in React?

Time:04-27

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?

CodePudding user response:

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

  • Related