nluizsoliveira
nluizsoliveira

Reputation: 375

Persistent way for getting an Input Value using Hooks

I'm a beginner at React. I'm trying to build a component that recovers the text of an input and later on inserts it on the HTML.

import React, { useState } from 'react';

function InputGetter(){
    const [text, setText] = useState("")
    let typed = ""
    return(
        <div>
            <input type='text' onChange = {(e)=> typed = e.target.value}></input>
            <button onClick={() => setText(typed)}>Set Text</button>
            Text typed was "{text}"
        </div>
    )
}

export default InputGetter

Empty input

enter image description here

The code above works for clicks when there's a change triggered. However, when I try to double click it, even when there's content on the input, text somehow is set to "". I'm not sure why it happens. How can I make the textvariable content persistent?

enter image description here

Upvotes: 0

Views: 51

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

You have closure on text value within the onClick callback, to persist value between renders, you can use useRef hook, see Is there something like instance variables?.

function InputGetter() {
  const [text, setText] = useState('');
  const inputRef = useRef('');
  return (
    <div>
      <input type="text" ref={inputRef}></input>
      <button onClick={() => setText(inputRef.current.value)}>Set Text</button>
      Text typed was "{text}"
    </div>
  );
}

Upvotes: 1

Related Questions