I would like to do a form with select. I use hooks and I use react-select for this.
My problems: The fiel select don't show the default value. When I select value the field don't show it. When I click on submit button, no value are send.
I don't understand why, someone could help me please?
this is my code:
function SelectFieldRequired(name, value, onChange) {
let options = [
{value: "vitrine-cms", label: "Site vitrine CMS"},
{value: "vitrine-main", label: "Site vitrine sur-mesure"},
{value: "eCommerce", label: "Site eCommerce"},
{value: "autre-site", label: "Autre site"},
{value: "ponctuel", label: "Mission ponctuelle"},
{value: "maintenance", label: "Maintenance"},
{value: "autre", label: "Autre choix"},
]
return(
<>
<div>Nature de la demande *</div>
<Select
name={name}
value={value}
defaultValue={options[1]}
onChange={onChange}
required
options={options}
/>
</>
)
}
export default function ContactForm() {
const [form, setForm] = useState({
lastName: "",
to_name: "service_........",
firstName: "",
company: "",
phone: "",
email: "",
natureOfTheRequest: null,
message: "",
acceptCGU: false,
});
const sendEmail = (e) => {
e.preventDefault();
emailjs
.sendForm(
"service_........",
"template_......",
e.target,
"user_........"
)
.then(
(result) => {
console.log(result);
alert("Email bien envoyé!!!");
},
(error) => {
console.log(error);
}
);
e.target.reset();
};
return (
<div className="container">
<form onSubmit={sendEmail}>
}
<SelectFieldRequired
className="request col-12"
name="natureOfTheRequest"
value={form.natureOfTheRequest}
onChange={setForm}
id="natureOfTheRequest"
/>
{/* SUBMIT button */}
<button
type="submit"
id={styles.submitButton}
className="btn btn-primary"
>
{" "}
Envoyer le formulaire
</button>
</form>
</div>
);
}
Thank you for your help.
You're setting the Select
value to form.natureOfTheRequest
, so you need to update that specific field on its onChange
callback, rather than simply passing setForm
.
The callback could look like the following.
const onChange = (value) => {
setForm((prevForm) => ({
...prevForm,
natureOfTheRequest: value
}));
};
Then, modify the SelectFieldRequired
's onChange
prop to receive it.
<SelectFieldRequired
className="request col-12"
name="natureOfTheRequest"
value={form.natureOfTheRequest}
onChange={onChange}
id="natureOfTheRequest"
/>
Since you're explicitly setting the value on the Select
, that also overrides the defaultValue
you have set. Instead, you can set the form.natureOfTheRequest
initial value to options[1]
.
const [form, setForm] = useState({
lastName: "",
to_name: "service_........",
firstName: "",
company: "",
phone: "",
email: "",
natureOfTheRequest: options[1],
message: "",
acceptCGU: false,
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.