0

I have a problem with getAttribute() in my React code.

const handleChange = (event) => {
        let selectM = event.target.getAttribute("data-minister_name");
        console.log(selectM);
    };

<List dense sx={{ width: '100%', maxWidth: 360, bgcolor: 'background.paper' }}>
                        {listMiniters.map((c) => (
                            <ListItem
                                key={c.label}
                                disablePadding
                                onClick={handleChange}
                                data-minister_name="{c.label}"
                            >
                                <ListItemButton>
                                    <ListItemAvatar>
                                        <Avatar
                                            alt={`Avatar n°${c.label + 1}`}
                                            src={`https://flagcdn.com/w20/${c.code.toLowerCase()}.png`}
                                        />
                                    </ListItemAvatar>
                                    <ListItemText id={c.label} primary={`Line item ${c.label + 1}`} />
                                </ListItemButton>
                            </ListItem>
                        ))}
                    </List>

It return to my

null

I don't understand where come from the problem...? Could you help my please ?

I'm using MUI.

2
  • 1
    If you console.log event.target can you see the attribute data-minister_name? Commented Feb 24, 2022 at 14:44
  • You right @Magofoco, I get a Div without my data-attribute. I didn't except that. Do you know why it doesn't appear ? Commented Feb 24, 2022 at 15:03

2 Answers 2

2

The event.target will be the element that was actually clicked which isn't, necessarily, the same as the element to which the event handler was bound.

The ListItem has a number of descendant elements which will intercept the click and be the event.target.

Use event.currentTarget instead.

Sign up to request clarification or add additional context in comments.

3 Comments

If I code : event.currentTarget.getAttribute("data-minister_name") it return {c.label}. That it is my code, but not the value I add in. Do you have more tips please ?
="{c.label}" — you're assigning a string with that value. If you don't want a string, don't use quotes.
OMG you totaly right. Thar work now. Basic mistake at the end of the day. Thank you very much to your help.
-1

Please try without '_' in your attribute name.

Altrernatively try with e.target.attributes.getNamedItem("aatribute-name").value;

1 Comment

I tried, but that change nothing TT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.