Answer the question
In order to leave comments, you need to log in
How to get value from hidden input in React?
It’s clear to me that in order to get the value from a regular input, you need to call a method through the onChange event, which, through event.target.value, will write its value to the state.
What event to use for input of type hidden to call the method? After all, you can’t bind onChange to it, since it is not editable
Answer the question
In order to leave comments, you need to log in
I don’t know how it’s done in a human way, but the refs helped.
Thus, this.hiddenInput.value
"some value" will lie in
https://codesandbox.io/embed/jolly-bose-rvyzh
Just don't beat me for this))
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [value, setValue] = React.useState("");
const [hidden, setHidden] = React.useState("");
const ref = React.useRef();
function onInput(event) {
setValue(event.target.value);
}
React.useEffect(() => {
const observer = new MutationObserver(list => {
for (const mutation of list) {
if (mutation.attributeName === "value") {
setHidden(ref.current.value);
}
}
});
observer.observe(ref.current, {
attributes: true
});
return () => {
observer.disconnect();
};
}, []);
return (
<div className="App">
<div>Hidden: {hidden}</div>
<input type="text" value={value} onInput={onInput} />
<input type="hidden" value={value} ref={ref} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question