I want to get input value and put them in json but I don't know how to get input value in this case
if I tried document.querySelector("todo-text").value It turns out to error.
const NewTodo: React.FC<NewTodoProps> = (props) => {
/* const textInputRef = useRef<HTMLInputElement>(null); */
const formData = new FormData();
const photos = document.querySelector('input[type="text"][multiple]');
const data = {
word: document.querySelector<HTMLInputElement>("todo-text").value,
meaning: document.getElementById("todo-meaning"),
};
const handleSubmit = async () => {
const body = JSON.stringify(data);
debugger;
const response = await fetch("https://localhost:5001/api/vocas", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
//mode: "cors", // no-cors, *cors, same-origin
//cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
//credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
Accept: "*/*",
},
//redirect: "follow", // manual, *follow, error
//referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: body, // 本文のデータ型は "Content-Type" ヘッダーと一致する必要があります
});
debugger;
const result = await response.json();
console.log(result);
return;
};
return (
<form onSubmit={handleSubmit}>
<div className="form-control">
<label htmlFor="todo-text">単語:</label>
<input type="text" id="todo-text" />
<br />
<label htmlFor="todo-meaning">意味:</label>
<input type="text" id="todo-meaning" />
</div>
<button type="submit">追加</button>
</form>
);
};
in this case, how to get input value??
We need to use useState to get the capture the userinput
import {useState} from 'react';
const[toDoText,setToDoText] = useState("");
in input field add a onChange Event
const handleInput = (event : React.ChangeEvent<HTMLInputElement>) => {
let target = event.target;
setToDoText((currentState) => {
return target.value;
})
}
<input type="text" id="todo-text" onChange={handleInput} />