Skip to content

Instantly share code, notes, and snippets.

@myogeshchavan97
Last active April 4, 2021 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myogeshchavan97/cb2cb479e27629c71259126a5d96b3b3 to your computer and use it in GitHub Desktop.
Save myogeshchavan97/cb2cb479e27629c71259126a5d96b3b3 to your computer and use it in GitHub Desktop.
useRef Demo
import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";
const App = () => {
const [username, setUsername] = useState("");
const usernameRef = useRef();
const handleOnSubmit = event => {
event.preventDefault();
setUsername(usernameRef.current.value);
usernameRef.current.value = "";
};
return (
<div>
<form onSubmit={handleOnSubmit}>
<input
type="text"
name="username"
placeholder="Enter your name"
autoComplete="off"
ref={usernameRef}
/>
<button>Submit</button>
</form>
<p>{username}</p>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment