Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
How can I get the value of a select form element?

I am trying to populate a select list dropdown in a form with results from an axios call in my action creator. The call populates a (sub)object in my redux store, then is used to populate the list. It is working fine, but I'm having trouble getting the value of the default list item, i.e. the value of the list item when the onchange event isn't fired.

At the moment the value attribute being controlled by selectedProject seems to have no affect at all. I.E. selectedProject remains an empty string but the first item in the select list is the first in the redux store.

It works fine if the user clicks the dropdown and fires the onChange, but there will be many circumstances where the default value is selected by the user. How can I get it?

Thanks very much for reading!

So far my code is:

  const { projects, newProject } = useSelector((state) => state.project)
  const [selectedProject, setSelectedProject] = useState('')

  useEffect(() => {
    dispatch(getProjects())
  }, [dispatch])

  const handleNavigate = (e) => {
    e.preventDefault()
    navigate(`/project/${selectedProject}`)
  }

return (
    <>
      {projects && (
        <>
          <form onSubmit={handleNavigate}>
            <select
              name='projects'
              id='project-list'
              onChange={(e) => setSelectedProject(e.target.value)}
              value={selectedProject}
            >
              {projects.map((project) => (
                <option key={project._id} value={project.title}>
                  {project.title}
                </option>
              ))}
            </select>
            <button>Go!</button>
          </form>
        </>
      )}
</>)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since your select input is being controlled by selectedProject that means, what is the value of that state, that is the value of select input. In your case initial value of state is an empty string, and that is de facto value.

What you are expecting is for React to automatically select the first element from projects list as your fist value. That is not how select element and react work. Even aside from React, that is just not how things work.

The correct way of seeing this is to always rely on your state that you assign for value prop. Here is the corrected version of your code:

const { projects, newProject } = useSelector((state) => state.project);
const [selectedProject, setSelectedProject] = useState('');

useEffect(() => {
  dispatch(getProjects());
}, [dispatch]);

useEffect(() => {
  if(projects && projects.length !== 0 && selectedProject !== '') {
    setSelectedProject(projects[0].title)
  }
}, [projects])

const handleNavigate = (e) => {
  e.preventDefault();
  navigate(`/project/${selectedProject}`);
};

In the code above, selectedProject is set to the first element of the array when the projects state is retrieved from redux.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda