Home > Blockchain >  How do I get value of an element after clicking another?
How do I get value of an element after clicking another?

Time:10-26

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:

You can use Codesandbox Demo

  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

Codesandbox Demo

  const inputRef = useRef("");

  const getValue = () => console.log(inputRef.current.value);

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={getValue}>get value</button>
    </div>
  );
  • Related