2

<ul>
    {
        this.state.pics ? this.state.pics.map((pic, index) => {
            return (
                <li key={index}>
                    <img src={pic.url} height="200" alt="Image preview..." />
                    <select data-id={index} onChange={this.setValue}>
                        <option value="1" >Monday</option>
                        <option value="2">Tuesday</option>
                        <option value="3">Wednesday</option>
                        <option value="4">Thursday</option>
                        <option value="4">Friday</option>
                        <option value="4">Saturday</option>
                        <option value="4">Sunday</option>
                    </select>
                </li>
            )
        }) : ""
    }
</ul>

On every change, I would like to get the value of data-id attribute which is nothing but value of index . or is there a way to directly access the value of key attribute of li . I am using react . Also is it a good practice in react to directly access the dom by query selector

pKay
  • 1,832
  • 4
  • 16
  • 23
  • Possible duplicate of [JavaScript: How to get parent element by selector?](https://stackoverflow.com/questions/14234560/javascript-how-to-get-parent-element-by-selector) – Andrea Carraro Nov 29 '17 at 18:30

3 Answers3

1
const setValue = (e) => {
 console.log(e.target.getAttribute('data-id'))
}

The onChange callback gets the normal javascript event object which can be used to access the attribute you want.

Shriharsha KL
  • 317
  • 1
  • 2
  • 11
0

Apart from pure JS based solutions of accessing the DOM via event APIs (in your case), you can also use the Refs feature of React

But as the docs themselves say

Avoid using refs for anything that can be done declaratively.

In your case, accessing the select element's custom attributes are pretty straightforward

  1. Create a ref to the element you wish to access the DOM

  2. Assign it to a variable which is accessible in your event callback

  3. Access the variable ,which has the DOM reference in your function.

    <select ref={select => (this.selectElement = select)} data-id={1} onChange={this.setValue}>

A sample can be found here in the CodeSandox link

And to answer your other question "Also is it a good practice in react to directly access the dom by query selector" - I'd say use that as a last resort , most of the problems can be solved by moving around props and states in component heirarchy.

Recommended reading

  1. Lifting State Up
  2. Thinking in React
semuzaboi
  • 4,972
  • 5
  • 20
  • 35
-2

You could try something like this $(this).parent().attr('data-id');

wbrandt
  • 149
  • 2
  • 13