React/MaterialUI - How can I edit my multiple-input to display a different placeholder other than those in my options?

Viewed 169

I have an inputfield/dropdown menu that takes in two JSON objects, symbol and company.

export default function SymbolInput() {

    const [data, setData] = useState({ companies: [] });

    const classes = useStyles();

    useEffect(() => {
        Axios.get("https://app.url.io/").then((res) => {
            setData({ companies: res.data });
        });
    }, [setData]);
    

    return (
        <div className={classes.root}>
            <Autocomplete
                multiple
                options={data.companies}
                getOptionLabel={(option) => option.symbol + ' | ' +  option.company}
                filterSelectedOptions
                renderInput={(params) => (
                <TextField
                    {...params}
                    variant="outlined"
                    label="Companies"
                />
                )}
            />
        </div>
    );

How it looks like:

enter image description here

I'd like to keep the dropdown menu as is, and when a user selects or enters a field using the textfield, I want the company symbols only to appear as the placeholder, not symbol + company name.

So as an example, the placeholders for the above image would be A AAPL ABBV ABMD

How may I be able to achieve that?

1 Answers

Looking at your sample code, it looks like AutoComplete's prop getOptionLabel is the function that renders the label.

Right now it's

getOptionLabel={(option) => option.symbol + ' | ' +  option.company}

So to only show the symbol, it probably would just be

getOptionLabel={(option) => option.symbol}

EDIT: It looks like AutoComplete also accepts a renderOption prop. Use both if you want the dropdown elements and the textfield to have different renders.

getOptionLabel={(option) => option.symbol + ' | ' +  option.company}
renderOption={(option) => option.symbol}

EDIT 2: If you want custom behavior, you have to track the search text yourself and use the filterOptions prop and create your own search function. Here is a codesandbox of a functional example. You have to tailor it to your own needs.

https://codesandbox.io/s/material-demo-forked-4ibur?file=/demo.js

Related