Answers for "useref get element"

32

useRef

/*
	A common use case is to access a child imperatively: 
*/

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Posted by: Guest on March-29-2020
1

example react useRef

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function CountMyRenders() {
  const countRenderRef = useRef(1);

  useEffect(function afterRender() {
    countRenderRef.current++;
  });

  return <div>I've rendered {countRenderRef.current} times</div>;
}

function App() {
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      <CountMyRenders />
      <button onClick={() => setCount(count => count + 1)}>
        Click to re-render
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Posted by: Guest on July-22-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language