I'm trying to create a web application that will have an entry field to collect a name, a button to submit, and an area to display a result message. I'm using a form styled with bootstrap and when using the onSubmit the form is not doing anything, however if I change the form to "onClick" it displays a Name:UUID, which is exactly the output I want. React On Submit picture React On Click picture Can someone please help me understand why this is happening and how to fix it? How do I get the name and uuid to display when the form is submitted? Please see my code and screenshots below:
...
import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { v4 as uuidv4 } from 'uuid';
import "./form.css";
function Form() {
const [name, setName] = useState("");
const [uuid, setUuid] = useState("");
const handleSubmit = (e) => {
// Preventing the default behavior of the form submit
e.preventDefault();
// Getting the value and name of the input which triggered the change
const { target } = e;
const inputType = target.name;
const inputValue = target.value;
// use input to save
if (inputType === "name") {
setName(inputValue);
setUuid(uuidv4());
}
e.preventDefault();
};
return (
<div className="container">
<form onSubmit={handleSubmit}>
<div className="row instructions text-left">
<div className=" col-sm-2 d-flex justify-content-between"></div>
<div className=" col-sm-10 d-flex justify-content-between">
<label>Please enter your name below:</label>
</div>
</div>
<div className="row">
<div className="col-sm-2 label-font">
<label className="label-font name" value="name">
Name:
</label>
</div>
<div className="col-sm-5">
<div className="row">
<input
name="name"
type="name"
className="form-control"
placeholder="Type your name here (with no spaces)"
></input>
</div>
<div className="row">
<button
type="submit"
className="btn-success btn-lg"
>
Submit
</button>
</div>
</div>
</div>
</form>
<div className="row">
<div className=" col-sm-2 label-font">
<label className="label-font">
Result:
</label>
</div>
<div className=" col-sm-10 result-output">
<label className="result-output">
{name}: {uuid}
</label>
</div>
</div>
</div>
);
}
export default Form;
...
CodePudding user response:
Your event is for the whole form, not for the input field.
Here is the way with minimal changes of your code:
const handleSubmit = (e) => {
// Preventing the default behavior of the form submit
e.preventDefault();
// Getting the value and name of the input which triggered the change
const inputValue = e.target.name.value;
// use input to save
setName(inputValue);
setUuid(uuidv4());
};
A link to the working playground: https://codesandbox.io/s/sleepy-austin-4w9iv?file=/src/App.js