Ciaran Crowley
Ciaran Crowley

Reputation: 419

How to style a Material-ui Autocomplete component

I have this Autocomplete component which is used in three different locations on the same page. All three require different styling. How can I pass styling from where the Autocomplete is rendered to its component file?

This is how the Autocomplete field is called and rendered:

<EmployeeSearch
    badge={details?.Owner|| ""}
    label="Owner"
    required
    id="Owner"
    onChange={onEmployeeChange}
    styling={{
        marginTop: "16px",
        width: "430px",
        fontSize: "12px",
    }}
    status={Status}
/>

Autocomplete component (trimmed down to properties which only affect styling:

function EmployeeSearch(props) {
    const { onChange, badge, label, id, disabled, styling, status, ...other } = props;
    const classes = useStyles();

    return (
        <Box>
            <Autocomplete
                InputProps={{ classes: { input: classes.fields } }}
                renderInput={(params) => ( <TextField {...params} /> )}
                classes={{ input: styling }}
                {...other}
            />
        </Box>
    );
}

Upvotes: 0

Views: 576

Answers (1)

Ahmad
Ahmad

Reputation: 1479

here you can see the live example

<EmployeeSearch
    badge={details?.Owner|| ""}
    label="Owner"
    required
    id="Owner"
    onChange={onEmployeeChange}
    styling={{
        marginTop: "16px",
        width: "430px",
        '.MuiAutocomplete-input': {
           fontSize: '12px !important'
        }
    }}
    status={Status}
/>

<EmployeeSearch
    badge={details?.Owner|| ""}
    label="Owner"
    required
    id="Owner"
    onChange={onEmployeeChange}
    styling={{
       marginTop: "16px",
       width: "500px",
       '.MuiAutocomplete-input': {
           fontSize: '12px !important'
        }
   }}
   status={Status}
/>

I think you have to change classes={{ input: styling }} to sx

function EmployeeSearch(props) {
    const { onChange, badge, label, id, disabled, styling, status, ...other } = props;
    const classes = useStyles();

    return (
        <Box>
            <Autocomplete
                InputProps={{ classes: { input: classes.fields } }}
                renderInput={(params) => ( <TextField {...params} /> )}
                sx={styling}
                {...other}
            />
        </Box>
    );
}

Upvotes: 1

Related Questions