Saturday, 19 February 2022

ListItem child doesn't fill full parent height - click counts as exit/escape

I've implemented a drawer similar to the example shown here. Everything works as expected, except if you click on the top/bottom edge of a ListItem - in that case, I'm not able to get to the value assigned to the ListItem, and it's treated like an escape/cancellation and closes the drawer.

Example of one of the list items:

<Collapse in = {isOpen} timeout = 'auto' unmountOnExit>
    <List component = 'div' disablePadding>
        <ListItem button key = {'Something'} value = {'Something'} sx =  onClick = {(e) => handleSelect(e)}>
            <ListItemIcon><StarBorder /></ListItemIcon>
            <ListItemText primary = {'Something'} />
        </ListItem>
    </List>
</Collapse>

Overall structure of the drawer:

<List>
    <Box>
        <ListItem />
        <Collapse>
            <ListItem />
            <ListItem />
        </Collapse>
    </Box>
</List>

onClick:

const handleSelect = (e) =>
{
    const parentTag = e.target.tagName

    if (parentTag === 'DIV')
    {
        console.log(e.target.innerHTML)

        for (let child of e.target.children)
        {
            if (child.tagName === 'SPAN')
            {
                console.log(child.innerHTML)
            }
        }
        
    }
    else if (parentTag === 'SPAN')
    {
        console.log(e.target.innerHTML)
    }
}

If you were to click in the middle of a ListItem, then parentTag === 'SPAN', and the console will log Something as expected.

But if you click on the top or bottom edge, then parentTag === 'DIV', and console.log(e.target.innerHTML) will show the following:

<div class="MuiListItemIcon-root..."><svg class="MuiSvgIcon-root..."><path d="..."></path> 
</svg></div><div class="MuiListItemText-root..."><span class="MuiTypography-root...">
Something
</span></div><span class="MuiTouchRipple-root..."><span class="css..."><span 
class="MuiTouchRipple..."></span></span></span>

There are three <span> elements, and I need the value of the first. However, console.log(child.innerHTML) always logs the later ones:

<span class="css..."><span 
class="MuiTouchRipple..."></span></span>

Is there a way to get to the actual value I need? Or a better way to handle this, maybe by making the <div> unclickable/expanding the click area of the ListItem?



from ListItem child doesn't fill full parent height - click counts as exit/escape

No comments:

Post a Comment