akibo
akibo

Reputation: 715

use ref to programmatically fire click event?

I have 2 buttons, I expect I can fire click event through ref.

const Button = ({ ref }) => (
  <button onClick={() => alert("btn 2 clicked")} ref={ref}>
    btn 2
  </button>
);
export default function App() {
  const btnRef = useRef(null);
  return (
    <div className="App">
      <button
        onClick={() => {
          btnRef && btnRef.current && btnRef.current.click();
        }}
      >
        btn 1
      </button>
      <br />
      <br />
      <Button ref={btnRef} />
    </div>
  );
}

but it doesn't work, what am I missing here? https://codesandbox.io/s/async-silence-ns9mg?file=/src/App.js:62-502

Upvotes: 2

Views: 1063

Answers (1)

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

You need to use React.forwardRef()

const Button = React.forwardRef((props, ref) => (
  <button onClick={() => alert("btn 2 clicked")} ref={ref}>
    btn 2
  </button>
));

Example: https://codesandbox.io/s/affectionate-tdd-5znpf

Upvotes: 3

Related Questions