defaultValue={Option[0]} doesn't work for Select component of UI Kit 2

Hi,
I’m expecting the Select component to be selected with the 1st option when loading the page. I used defaultValue={Option[0]} , but it doesn’t work. Could anyone help?

          <Select inputId='projectKey-select' name="projectKey" placeholder='Please select a project'
            isRequired={true} onChange={handleProjectSelect} spacing='default' defaultValue={Option[0]}
            options=
            {projectData?.length > 0 ?
              projectData.map((project) => (
                { label: project.projectName, value: project.projectKey }
              ))
              :
              []
            }
          />

Thanks,
YY

Hi @YY1,

Hmm… I totally see what you’re trying to do, based on the documentation. I’ll dig in a little deeper to better understand that interface.

I do, however, have a workaround. If you use the original projectData object, you can do something like this:

  defaultValue={{ label: projectData[0].projectName, value: projectData[0].projectKey }}

That seems to work for me.

1 Like

Hi, could you share what is the Option object that you’re trying to access with Option[0]? I’ve tried with something like:

const options = [
  {label: 'A', value: 'a'},
  {label: 'B', value: 'b'},
  {label: 'C', value: 'c'}
]

and setting options[0] as defaultValue works for me.

1 Like

Hi @yongchong.long, indeed. Your example does work if his object had those key names; however, it appears as though his object is shaped like this:

  const projectData = [
    { projectKey: 'PROJ1', projectName: 'Project1' },
    { projectKey: 'PROJ2', projectName: 'Project2' },
    { projectKey: 'PROJ3', projectName: 'Project3' }
  ];

By the way, I think it is very important that both the label and value is set (in defaultValue) in order to truly have the item selected. I mention this because you can set just the label and it appears to be pre-selected; however, I don’t believe that option is truly selected.

4 Likes

Thanks guys. Your solutions work for me.