javascriptreactjsshopifypolaris

Shopify Polaris: Select component doesn't update selected option when options are dynamic


The Select component of Polaris works well when the options are defined on load, as you can see in the documentation.

However if the options are created dynamically, eg. fetched from an external source, the selected option's label is not updated after we select an option, the selected option's value is recognized correctly. Please check the live sandbox here. Do you know how to solve this? Thanks!


Solution

  • That's because handleSelectChange receives the new value as a string while in your fetched options array the value property is a number.

    <Select /> component cannot find the selected value because the types don't match.

    Just convert your IDs to strings:

    json.forEach((item: any) => {
        _options.push({
            label: item.title,
            value: item.id.toString()
        });
    });