Home > other >  Set custom html attribute to child element of material ui component
Set custom html attribute to child element of material ui component

Time:09-08

I have to add the custom HTML5 attribute "data-metrics" to the span element, but I'm not sure how to achieve that using the ListItemText Material UI component. Component API Documentation: https://mui.com/material-ui/api/list-item-text/

This is my code at the moment:

<li>
  <ListItem button key={`list_item_${index}`}
    component={Link} to={data.url}
    activeClassName={classes.activeLink} partiallyActive={true}
    focusVisibleClassName={classes.buttonOnFocus}>
     <ListItemText primary={data.name} 
       data-metrics={`{"btnname":"${data.name.toLowerCase()}"}`}/>
  </ListItem>
</li>

And this is what it is generating: Attribute is being set to div element instead of span(child)

Note the data-metrics attribute is being set to the div element instead of the span.

CodePudding user response:

I think you need to use the "primaryTypographyProps" prop inside the component. At least I think that's what the docs are saying.

I think you need to pass it an object like so:

<ListItemText primaryTypographyProps={{"data-metrics": "test"}} />

CodePudding user response:

You can use useRef hook for this purpose, after you found an element in your ref.current object you can invoke ref.current.setAttribute("data-metrics", VALUE) It forwards ref to a root element

  • Related