Using React, how can I attach a click event to a class or ID? Using React, how can I attach a click event to a class or ID? reactjs reactjs

Using React, how can I attach a click event to a class or ID?


I don't think you should worry for with vanilla JS DOM manipulation in such cases, but if you want to make it react-ish you can use Context.

First define your context:

const CircleContext = React.createContext();

then wrap your app (or part of app where circles will be used) with CircleContext.Provider and set it's value to desired callback:

function App() {  return (    <CircleContext.Provider      value={e => {        console.log("Circle clicked!");      }}    >      <div className="App">        <Circle />      </div>    </CircleContext.Provider>  );}

And consume that context in your circle component (I used useContext hook):

function Circle() {  const context = useContext(CircleContext);  return <button onClick={context}>My Button</button>;}

With this implementation every Circle component will use same onClick handler defined in CircleContext.Provider.

Example code.