mayk93
mayk93

Reputation: 1537

React Material UI, how do I make mobile friendly selects?

I am working on a React project and I am using Material UI.

Versions:

├─ [email protected]
├─ [email protected]

I have in my code a component that makes use of Select Field component.

My code looks something like this:

<SelectField some_props>
    {some_list.map(() => {return <MenuItem other_props/>})}
</SelectField>

On a desktop, this looks very good. However, I would like to get the native mobile select. The rolling one.

Basically, this:

Roll select

How do I get a mobile friendly rolling select with Material UI?

Thanks!

Upvotes: 3

Views: 3430

Answers (1)

Alex
Alex

Reputation: 12433

Here is an example component which uses react-device-detect. If the user isMobile, the native select/options are rendered.

import React from 'react';
import {isMobile} from 'react-device-detect';

import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';

const ExampleSelect = () => {

    const value = null;
    const onChange = (e) => console.log(e.target.value);
    const options = [
        {value: 1, label: 'Option 1'},
        {value: 2, label: 'Option 2'},
        {value: 3, label: 'Option 3'}
    ];

    return (

        <FormControl>
            <InputLabel>
                Options
            </InputLabel>
            <Select
                native={isMobile}
                value={value}
                onChange={onChange}
            >
                {options.map(option => (
                    isMobile ? (
                        <option key={option.value} value={option.value}>{option.label}</option>
                    ) : (
                        <MenuItem key={option.value} value={option.value}>{option.label}</MenuItem>
                    )
                ))}
            </Select>
        </FormControl>

    )
}    

export default ExampleSelect;

Upvotes: 3

Related Questions