Search code examples
javascriptreactjsdomonclickgetelementbyid

ReactJS onClick get DIV IDs


I have 3 divs and onClick, I want to grab the ID of each div.

(Eventually, I want to add a shuffle function, to shuffle the divs). But for the time being, I just want to get the ID of each.

If I console.log this on each div onClick, I only seem to get the values of the last div. No matter which div I click.

What's the best way to do this?

I've read about React.createRef(), but this does not seem to generate a unique ID per div. (I've read it's best not to use document.getElementByID() in react).

So what's the best way to do this?

Here's my code so far!

import React, { useState } from 'react';

class Cylinders extends React.Component {

  constructor(props) {
    super(props);
    this.myRef = React.createRef();

    this.state = {
      ball: ''
    }
  }


  componentDidMount = () => {
    console.log('mount');
  }

  generateShuffle = () => {
    console.log('shuffel');
    console.log('this', this);
  }

  render() {
    return (
        <section>

          <div className="columns is-mobile">
            <div className="column">
              <h1 className="title has-text-black is-size-2">Cylinders Game</h1>
            </div>
          </div>

          <div className="columns is-mobile">
            <div className="column">
              <button className="title has-text-black is-size-2">Ball container</button>
            </div>
          </div>

          <div className="columns is-mobile">
            <div className="column">
              <div className="columns is-multiline">
                <div
                  onClick={this.generateShuffle}
                  className="hat1"
                  // ref="1"
                  ref={this.myRef}
                  id="1">
                </div>
              </div>
            </div>

            <div className="column">
              <div className="columns is-multiline">
                <div 
                  className="hat2" 
                  ref={this.myRef} 
                  id="2" 
                  onClick={this.generateShuffle}>
                </div>
              </div>
            </div>

            <div className="column">
              <div className="columns is-multiline">
                <div className="hat3" 
                  ref={this.myRef} 
                  id="3" 
                  onClick={this.generateShuffle}>
                </div>
              </div>
            </div>

          </div>
        </section>
    );
  }
}

export default Cylinders;

Solution

  • Maybe try a different approach and draw the elements from an array you can shuffle more easily, like that:

      const [things, setThings] = useState([
        { name: "Thing" },
        { name: "Other Thing" },
        { name: "Another Thing" }
      ]);
    
    
      const shuffle = () => {
        // shuffle things variables
        const shuffled = things.sort(() => Math.random() - 0.5);
        setThings([...shuffled]);
      };
    

    And render them :

       <div className="App">
          <div>
            <button onClick={shuffle}>Shuffle list</button>
          </div>
          {things.map((item, index) => {
            return (
              <div
                className="something"
                onClick={() => handleClick(item)}
                key={item.name + index}
              >
                {item.name}
              </div>
            );
          })}
        </div>
    

    It's written in functional component way, but you can see an example Here