Home > Blockchain >  How can I get the value of a select form element?
How can I get the value of a select form element?

Time:12-06

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>
        </>
      )}
</>)

CodePudding user response:

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.

  • Related