Search code examples
reactjstypescriptinputfocusblur

How to clone a state variable to use as a reference in react?


This is something I couldn't find a good answer on, but I solved it; this is the question:

I want to have an input element reset if not in focus

type Props = {
    inputRef: any;
    value: string;
    setValue: Function;
}

const inputField = (props: Props) => {
    let tempValue = props.value;
    
    return(
        <input
            ref= {props.inputRef}
            onChange= {e => 
                props.setValue(e.target.value);
            }
            value= {props.value}
            onBlur={ () => {
                props.setValue(tempValue);
            }}
        />
    )
}

but for some reason it doesn't clear the value

p.s. the inputRef, value, and setValue are hooks

const [value, setValue] = useState(...);
inputRef = useRef<HTMLInputElement>(null);

Solution

  • The given method doesn't work because the variable within the element is not being updated with the DOM.

    create a temporary state variable.

    type Props = {
        inputRef: any;
        // value removed because it's not necessary
        // setValue not necessary because value is no longer being changed, the
        // value will be changed in a seperate method that's called in someway
        // on the outer scope
    }
    
    const inputField = (props: Props) => {  
        const [value, setValue] = useState(""); // adding the useState hook here gives a inscope temp value
        return(
            <input
                ref= {props.inputRef}
                onChange= {e => 
                    setValue(e.target.value);
                }
                value= {value}
            />
        )
    

    it will set to whatever it's initialized as when you call the method. You can set a dynamic default value (useState("") -> useState(defaultValue)) out of scope. This solution also allows for the innerscope value to not affect the outerscope value that's desired for input, therefore isolating the input field and giving more control to some onSubmit(value: string) out of scope method.