Search code examples
material-uiautosuggest

is there an easy way to use theme colors in react-autosuggest items


I'm trying to use react-autosuggest as it is designed to be, for me, the method signature of renderSuggestion should contain the actual theme, so we can use variables from the theme in our styling

Here's my workaround, but I just want to be sure I'm not making something uselessly complex:

                                        <AutoSuggest
                                                renderSuggestion={createRenderSuggestion(this.props.classes)}
/>

the variable this.props.classes is populated at the component creation

withStyles(styles)(ShopSuggestBox)

an I had to define a method within a method to get access to the actual theme

const createRenderSuggestion = theme => suggestion => {
    console.log("setting css of name:", theme.itemName)
    return (
            <div>
                <div className={theme.itemName}>
                    {suggestion.name}
                </div>
                <div className={theme.itemInfo}>
                    NYC
                </div>
            </div>
    )
}

Just to be sure to be clear: when I attempt to access to the theme within the method function renderSuggestion(suggestion, { query, isHighlighted }) i can't


Solution

  • Have a look at https://material-ui.com/customization/themes/#accessing-the-theme-in-a-component.

    You could also use withStyles(styles, { withTheme: true })(ShopSuggestBox); if you don't want to compose.

    Either way the theme is then accessible in the props of you ShopSuggestBox.