Dynamic Dropdown Selection Options for forms using React.js

alexmcdgit

AlexMcD-git

Posted on October 6, 2022

Dynamic Dropdown Selection Options for forms using React.js

Drop down options on forms are an important aspect of the functionality of my react-redux/ruby on rails project, RuneScape themed task bingo, viewable here (hosted on heroku).

I found myself satisfied with the outcome and wanted to show how I built out the result starting at the HTML foundation up to dynamic use with react.
Starting with the basics of a form. (just the "select" and "submit" parts for this example even though it had more inputs in the project)

return(
      <form>
        <label>Which team are you submitting for? </label>
        <select name="team">
          <option>Select A Team</option>
          {//teams need to populate as <option> tags}
        </select>
        <button type="submit">Submit</button>
      </form>
)
Enter fullscreen mode Exit fullscreen mode

From there I would incorporate the react elements such as state and handling changes or submitting.

const [formState, setFormState] = useState(initialState)
function handleSubmit(e){
  e.preventDefault()
  //patch request to backend and reset form state
}
const handleChange = (e) => {
    const { name, value } = e.target
    setFormState((prevState) => ({...prevState, [name]: value}))
}
return(
      <form onSubmit={(e) => handleSubmit(e)}>
        <label>Which team are you submitting for? </label>
        <select name="team" value={formState.team} onChange={handleChange}>
          <option>Select A Team</option>
          {//teams need to populate as <option> tags}
        </select>
        <button type="submit">Submit</button>
      </form>
)
Enter fullscreen mode Exit fullscreen mode

Now we have the basics of a form that will keep its contents in state and send a patch request when submitted. The remainder of the options come from the active "game" that is held in the redux store. We pull that into this component with:

  const activeGame = useSelector ((state) => state.game.value)
Enter fullscreen mode Exit fullscreen mode

Since our game object has a board array, each with the associated team, we can just use .map to create components for each team to fill in the tag.

        <select name="team" value={formState.team} onChange={handleChange}>
          <option>Select A Team</option>
          {activeGame.boards.map(board => <option key={board.team.id}>{board.team.team_name}</option>)}
        </select>
Enter fullscreen mode Exit fullscreen mode

The intuitive nature of React made this fairly straightforward to do even after only a few months coding in javascript. If you have a different or better way of creating select options for forms please share below as I'm always looking to improve my own practices.

💖 💪 🙅 🚩
alexmcdgit
AlexMcD-git

Posted on October 6, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related