1

I have simple form with dropdown select menu. How do I reset the select field back to show first option after submission ( ---Select category---)? I have tried setCategory("") or setCategory("---Select category---") but it keeps showing category i have picked.

const [category, setCategory] = useState("");

  function formSubmit(e) {
    e.preventDefault();

    firebase
      .firestore()
      .collection("posts")
      .add({
        category,
      })
      .then(() => {
        setCategory("");
      });
  }

<form onSubmit={formSubmit}>
  <div>
    <label htmlFor="category">Post Category</label>
    <select
      name="category"
      onChange={(e) => setCategory(e.currentTarget.value)}
    >
      <option value="">--- Select category ---</option>
      <option value="react">React</option>
      <option value="CSS">CSS</option>
      <option value="misc">Misc</option>
    </select>

    <div>
      <button type="submit">Add</button>
    </div>
</div>
Timmy
  • 61
  • 7

1 Answers1

1

After doing a little bit of research I found this questions answered here, here, and here. However, I would advice you to use the react-advanced-form library which makes this task a lot easier and will give you more features to implement on your forms.

While using this library you want to use “form.reset()” on your action button. This will let you set initial values for each field and the action will set the values of your fields to this default value. Here is an example:

import React from 'react'
import { Form } from 'react-advanced-form'
import { Input } from 'react-advanced-form-addons'

export default class Example extends React.Component {
  handleSubmitted = ({ res, fields, form }) => {
    form.reset() // resets "username" field to "admin"
  }

  render() {
    return (
      <Form onSubmitted={this.handleSubmitted}>
        <Input
          name="username"
          initialValue="admin" />
      </Form>
    )
  }
}
Chris32
  • 4,716
  • 2
  • 18
  • 30
  • None of the answers helps me because I already tried that. Guess I will try library...was hoping it can be done in a simple way. Thanks for the help. – Timmy Aug 24 '20 at 15:03