<select> dropdown width change based on text size of options in React TypeScript

Viewed 33

I am facing a problem. In my TypeScript and React project, I want to adjust the width of the select dropdown based on the options text width. For example, for the option "Hello" the select size will be the same as "Hello". If the text is "I cannot do that" then the select size will be the same size. enter image description here

enter image description here

interfaces.ts

export interface Props {
  id: string;
  onChange: () => void;
  options: {
    label: string;
    value: string;
  }[];
  value: string;
}

template.tsx

export const Template = (props: Props) => {
  const { id, onChange, options, value } = props;

  const dropdownClass = clx(styles.iconDropdown);

  return (
    <select id={id} value={value} onChange={onChange} className={dropdownClass}>
      {options.map((option) => {
        return <option value={option.value}>{option.label}</option>;
      })}
    </select>
  );
};

Dropdown.stories.tsx


export default {
  argTypes: {
    backgroundColor: { control: "color" },
  },
  component: Template,
  title: "Atoms/Dropdown/Dropdown",
} as ComponentMeta<typeof Template>;

const StoryTemplate: ComponentStory<typeof Template> = (args: Props) => {
  return <Template {...args} />;
};

Dropdown.stories.tsx
export const Dropdown = StoryTemplate.bind({});
Dropdown.args = {
  options: [
    {
      label: "おすすめ順",
      value: "3",
    },
    {
      label: "料金が安い順",
      value: "0",
    },
    {
      label: "料金が高い順",
      value: "1",
    },
    {
      label: "ポイント付与率が高い順",
      value: "2",
    },
  ],
};

style.module.scss

.iconDropdown {
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border: 1px solid #8c8c8c;
  border-radius: 60px;
  width: fit-content;
  height: 36px;
  white-space: nowrap;
  padding: 10px 32px 10px 12px;

  font-family: "Hiragino Kaku Gothic Pro";
  font-style: normal;
  font-weight: 300;
  font-size: 14px;
  color: #333333;

  background: url(~/assets/dropdown-icon.svg) no-repeat right #ffffff;
  -webkit-appearance: none;
  background-position-x: calc(100% - 10px);
  line-height: 1;
}

select.iconDropdown:focus {
  outline: none;
}

0 Answers
Related