Search code examples
javascriptreactjsref

Click away listener with select component as a child


In example below there is container that contains few elements. Everything works fine instead of nested Select element. When clicking select, it detects as if the click happened outside the red container

Codesandbox example


Solution

  • The issue goes away if you use disablePortal on the Select. The reason is: by default mui uses a portal concept, which means popups are placed into a completely different DOM sub-tree (located as last child in the <body>). Well this royally messes with checking if bubbling events originated in the same subtree constituted by your component or are considered outside clicks.

              <Select
                labelId="demo-simple-select-label"
                id="demo-simple-select"
                value={age}
                label="Age"
                onChange={handleChange}
                MenuProps={{disablePortal: true}}
              >
                <MenuItem value={10}>Ten</MenuItem>
                <MenuItem value={20}>Twenty</MenuItem>
                <MenuItem value={30}>Thirty</MenuItem>
              </Select>