useRef
by Matt Tyson
HTML
<div id="root" />
CSS
input {
width: 200px;
border: 1px solid #ccc;
padding: 10px;
font-size: 16px;
}
button {
background-color: #42b983;
color: white;
border: none;
padding: 10px;
cursor: pointer;
margin: 10px;
}
div {
font-size: 20px;
margin-top: 10px;
font-family: Fira Code, Consolas, Source Code Pro, monospace;
}
React
const App = () => {
const inputRef = React.useRef(null);
const handleClick = () => {
inputRef.current.focus();
inputRef.current.value="Something amazing";
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<App/>
);