1

There are multiple divs on a page. What I want to do is get an attribute when a div is clicked. It is very easy in jquery but I am using Reactjs. Here is my code. It works but every time when I click on div attribute of the last element in is returned. Following is my code and the codepen URL. https://codepen.io/anon/pen/gepVNP?editors=0010

class Content extends React.Component{
  constructor(props) {
    super(props)
    this.click = this.click.bind(this)
  }
  click(){
    // this.prop.setActiveMenu();
    var summary = this.refs.summary;
    console.log(summary.getAttribute('data-slug'))
  }
    render(){
        return(
          <div className="content">
            {posts.map((post)=>{
                return (
                    <div ref="summary" data-slug={post.slug} onClick={this.click} key={post.slug}>
                        <h1>{post.title}</h1>
                        <div>{post.content}</div>
                        <br/><br/><br/><br/><br/>
                    </div>
                );
            })}
          </div>
        );
    }
}
mysterious
  • 1,450
  • 5
  • 29
  • 56
  • Ref strings are deprecated for newest versions of react. I believe that ref names must be unique and therefore overriding all your previous refs. You will need to assign it using an index in your template, use the ref callback function, extract it to a component with a event props or just use the simple click event and extract value from the target. – Jonathan Hamel Mar 12 '18 at 13:27

2 Answers2

1

That's because you're changing the ref element inside the map everytime you iterate on the posts array. No need for refs here IMO.

Why not use the event.target from the click event?

onClick(event){
   console.log(event.target.getAttribute('data-slug'))
}

BTW: String refs are considered legacy. have a look here: Why ref='string' is "legacy"?

Matan Bobi
  • 2,693
  • 1
  • 15
  • 27
0

I discourage you from using this approach, you could use a component instead.

The ref prop accepts a function and return the ref, so passing a string doesn't work.

class Content extends React.Component{
  constructor(props) {
    super(props)
    this.click = this.click.bind(this)
  }
  click(){
    console.log(this.summary.getAttribute('data-slug'))
  }

    render(){
        return(
          <div className="content">
            {posts.map((post)=>{
                return (
                    <div ref={ref => this.summary = ref} data-slug={post.slug} onClick={this.click} key={post.slug}>
                        <h1>{post.title}</h1>
                        <div>{post.content}</div>
                        <br/><br/><br/><br/><br/>
                    </div>
                );
            })}
          </div>
        );
    }
}
giggi__
  • 1,793
  • 1
  • 11
  • 12