How do you do this in React?

From this example:


I now have the following, the purpose of which is to give each button a unique Id and alert that Id when the button is clicked. How would you do this in react:

<!DOCTYPE html>

<p>Click the button to make a BUTTON element with text.</p>

<button onclick="myFunction()">Try it</button>

var count = 0;
function myFunction() {
  let count2=count;
  var btn = document.createElement("BUTTON");
  btn.innerHTML = "CLICK ME";
  btn.onclick = function(){
    alert('you cliked button with id : '+ count2)


React is all about components and state. I’d say a good direction is to start thinking what components you’ll need to create, and what state you want to keep track of (and display).

A good read from the official documentation(Thinking in React)

A more basic example would be.

Your JSX.

<button onClick={() => {alert("Hi I am an alert")}}>Button</button>

You would pass in a callback function to handle your logic on onClick handler.

React discourages directly interacting with the DOM, or even using event-listeners directly as it uses a virtual DOM and has ‘synthetic’ events, but there some unavoidable cases that you would have to interact with the DOM directly (ex. canvas, scrolling , etc…) . But for your example there would be no reason to interact with the DOM directly, here is one way to implement it in React

The above code re-renders all the buttons on each state change, one could optimize it to render only the newly added buttons however…

I took a slightly different approach as @Dereje1 with regards to what I stored in state.

class App extends React.Component {   
  constructor(props) {
    this.state = {
      buttonIds: []
  handleClick = () => {
    this.setState(({ buttonIds }) => ({
      buttonIds: [...buttonIds, buttonIds.length]
  render () {
    return (
        <p>Click the button to make a BUTTON element with text.</p>
        <button onClick={this.handleClick}>Try it</button>
        { => <Button key={id} id={id} />)}

const Button = ({ id, handleButtonClick }) => {
  return (
    onClick={() => alert('you clicked button with id : '+ id)}
  >Click Me

ReactDOM.render(<App />, document.getElementById('root'));

@RandellDawson, your code is much cleaner, but I believe all the buttons are still re-rendered with each render like mine, if there are 1000 buttons, then on every render (state change) all 1000 buttons would be rendered just to render the 1001th button, I think it would be beneficial to just render the new button only

I agree that it show only render a new button. I will think about it how best implement.

On second thought , it may not be as expensive as I thought, since react computes the differences and then renders only the differences

So, even though the render function would loop through all the buttons , I think react only renders the differences from the previous DOM representation after computing what changed