use ref to programmatically fire click event?

Viewed 587

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

1 Answers
Related