'React: Set a select input back to the default value after submitting
I have a React.js question about how to set a select input back to the default value after a user clicked a submit btn.
in my form, there are several inputs and I could set the inputs back to an empty showing each placeholder except and tag. When users clicked a submit btn, it calls a handleSubmit function and by calling setValues() function at the end of handleSubmit function, all input values are gone except input.
I wanna set it to "Select a category".
Here is my code for and related functions. Thanks for your comment and valuable time in advance.
FormInputSelect.jsx
import React from 'react';
const FormInputSelect = props => {
const { label, onChange, id, ...inputProps } = props;
return (
<div className='quizFormInputSelect'>
<label>{label}</label>
<select name={label} id={label} onChange={onChange} defaultValue="">
<option value="default" disabled>Select a category</option>
<option value="Workout">Workout</option>
<option value="Muscle">Muscle</option>
<option value="Nutrition">Nutrition</option>
<option value="Other">Other</option>
</select>
</div>
);
};
export default FormInputSelect;
NewQuiz.jsx
import { useState } from 'react';
import { collection, setDoc, doc, addDoc } from 'firebase/firestore';
import FormInputText from './FormInputText';
import FormInputSelect from './FormInputSelect';
import db from '../firebaseConfig';
const NewQuiz = () => {
const [values, setValues] = useState({
question: '',
answer1: '',
answer2: '',
answer3: '',
answer4: '',
correctAnswer: 0,
createdAt: '',
category: ""
});
const inputs = [
{
id: 1,
name: 'question',
type: 'text',
placeholder: 'Is protein powder white happy magical snow??',
label: 'Question',
},
{
id: 2,
name: 'answer1',
type: 'text',
placeholder: 'No',
label: 'Answer 1',
},
{
id: 3,
name: 'answer2',
type: 'text',
placeholder: 'Yes',
label: 'Answer 2',
},
{
id: 4,
name: 'answer3',
type: 'text',
placeholder: 'Maybe',
label: 'Answer 3',
},
{
id: 5,
name: 'answer4',
type: 'text',
placeholder: 'Tqm',
label: 'Answer 4',
},
{
id: 6,
name: 'correctAnswer',
type: 'number',
placeholder: 1,
label: 'Correct Answer',
},
{
id: 7,
name: 'category',
label: 'Category',
},
];
const onChange = e => {
setValues({ ...values, [e.target.name]: e.target.value });
};
const handleSubmit = async e => {
// const quizRef = doc(db, 'quizzes', 'category');
// await setDoc(quizRef, payload);
e.preventDefault();
const quizCollectionRef = collection(db, 'quizzes');
const payload = {
question: values['question'],
answers: [
values['answer1'],
values['answer2'],
values['answer3'],
values['answer4'],
],
correctAnswer: parseInt(values['correctAnswer']),
likes: 0,
createdAt: new Date(),
category: values['category']
};
await addDoc(quizCollectionRef, payload);
setValues({
question: '',
answer1: '',
answer2: '',
answer3: '',
answer4: '',
correctAnswer: 0,
createdAt: '',
category: "Select a category" // how to set it to default value
})
};
console.log(values);
return (
<form action='' className='quizForm' onSubmit={handleSubmit}>
{inputs.map((input, i) => {
if (input["type"] === "text" || input["type"] === "number") {
return (
<FormInputText
key={input.id}
{...input}
value={values[input.name]}
onChange={onChange}
/>
)
} else {
return (
<FormInputSelect
key={input.id}
{...input}
value={values[input.name]}
onChange={onChange}
/>
)
}
})}
<button>Submit</button>
</form>
);
};
export default NewQuiz;
Solution 1:[1]
You can put the default value in your state instead of an empty string. That way if anyone submits the form then the value of input will be back to its `default' value.
const [values, setValues] = useState({
category: "Select a category"
});
Solution 2:[2]
First you would need to add the default empty option in the <select>
<option value="">Select a category</option>
And then you need to clear it normally
setValues({
// ...
category: ""
})
Solution 3:[3]
Initialize it with a value like this,
const [values, setValues] = useState({
question: '',
answer1: '',
answer2: '',
answer3: '',
answer4: '',
correctAnswer: 0,
createdAt: '',
category: "default"
});
setValues({
question: '',
answer1: '',
answer2: '',
answer3: '',
answer4: '',
correctAnswer: 0,
createdAt: '',
category: "default" // Match it with value="____" in select
})
<select name={label} id={label} onChange={onChange} value={value}>
<option value="default" disabled>Select a category</option>
<option value="Workout">Workout</option>
<option value="Muscle">Muscle</option>
<option value="Nutrition">Nutrition</option>
<option value="Other">Other</option>
</select>
Note: As others mentioned, you can also initialize it with a empty string, but make sure you update it everywhere.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharmik Patel |
| Solution 2 | GMaiolo |
| Solution 3 | Shri Hari L |
