'Read data from form in custom react hook
How to get data from form in custom hook? I want to call useSearch hook in SearchProducts component and pass the submitted data. Is there any better solution for this?
function useSearch() {
const submitHandle = (event) => {
event.preventDefault();
let data = [];
const elements = event.target.childNodes;
elements.forEach((element) => {
data[element.name] = element.value;
element.value = "";
});
// I need data from form here.
console.log(data);
};
return {
onSubmit: submitHandle,
};
}
export default function SearchProducts() {
const search = useSearch();
return (
<Container>
<Form {...search}>
<Input name="searchInput" />
<SearchButton type="submit">search</SearchButton>
</Form>
</Container>
);
}
export default function Input({ type, name }) {
const input = useInput("");
return <InputField type={type} name={name} {...input} />;
}
function useInput(initialValue) {
const [value, setValue] = useState(initialValue);
const handleChange = (event) => {
if (value === false) {
setValue(true);
}
setValue(event.target.value);
};
return {
value: value,
onChange: handleChange,
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
