malejpavouk
malejpavouk

Reputation: 4445

Material UI: Menu refactoring

was trying to refactor my menu, which uses List from Material UI.

The unrefactored menu looks like this

    <SelectableList id="menu" value={location}>
    <ListItem primaryText="Encoding" primaryTogglesNestedList={true} value="/encoding" nestedItems={[
        <ListItem primaryText="Base32" containerElement={<Link to="/base32"/>} value="/base32"/>,
        <ListItem primaryText="Base32Hex" containerElement={<Link to="/base32Hex"/>} value="/base32Hex"/>,
        <ListItem primaryText="Base64" containerElement={<Link to="/base64"/>} value="/base64"/>,

and there is clearly a lot of boilerplate, so I decided to create a custom component, which would handle the duplicities in the code

import React from 'react';
import {ListItem} from 'material-ui/List'
import {Link} from 'react-router'

const MenuItem = ({anchor, ...other}) => (
    <ListItem containerElement={<Link to={anchor} />} value={anchor} {...other} key={"item-"+ anchor}/>
);


export default MenuItem;

The problem is, that when I used it

<MenuItem primaryText="Base32" anchor="/base32" />

The menuItem ceased to be selectable. Further more, to recall the value from SelectableList id="menu" value={location} (to expand the menu, when page is reloaded), I had to to add value tag to MenuItem as well (duplicity back).

How should I handle this refactoring?


Update JSFiddle (simplified example): https://jsfiddle.net/1vk8wzoc/27/

Upvotes: 0

Views: 603

Answers (1)

Chris
Chris

Reputation: 58142

Ok, so looking at your JSFiddle and the Material UI source, it seems like they reject children without certain properties:

https://github.com/callemall/material-ui/blob/master/src/List/makeSelectable.js#L18

extendChild(child, styles, selectedItemStyle) {
  if (child && child.type && child.type.muiName === 'ListItem') {
    ....

So your component is never receive the styles to indicate that its selected.

I would do one of two things here:

  1. Possibly raise a PR with the library to support HOC's for Listitems
  2. Or, use React.cloneElement which should copy all the required stuff across so it appears to be the right element to the makeSelectable function

Upvotes: 1

Related Questions