In React, how can I get the value of another element by clicking/changing a different one?
<div>
<input {get this value}/>
<button onClick={()=> console.log(get value of above input field)}/>
</div>
CodePudding user response:
const [inputValue, setInputValue] = useState("");
function onInputChange(e) {
setInputValue(e.target.value);
}
const getValue = () => console.log(inputValue);
return (
<div>
<input value={inputValue} onChange={onInputChange} />
<button onClick={getValue}>get value</button>
</div>
);
2) Uncontrollect input using useRef
hook
const inputRef = useRef("");
const getValue = () => console.log(inputRef.current.value);
return (
<div>
<input ref={inputRef} />
<button onClick={getValue}>get value</button>
</div>
);