Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react useref

import React, { useState, useRef, useEffect } from 'react'
import { render } from 'react-dom'

function App() {
  const intervalRef = useRef()
  const [count, setCount] = useState(0)

  useEffect(() => {
    intervalRef.current = setInterval(() => setCount(count => count + 1), 1000)

    return () => {
      clearInterval(intervalRef.current)
    }
  }, [])

  return (
    <>
      <div style={{ fontSize: 120 }}>{count}</div>
      <button
        onClick={() => {
          clearInterval(intervalRef.current)
        }}
      >
        Stop
      </button>
    </>
  )
}

render(<App />, document.querySelector('#app'))
Comment

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>
    </>
  );
}
Comment

useref

import { useRef } from "react";

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>
    </>
  );
}
Comment

useRef() in react

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>
    </>
  );
}
Comment

useRef

/**
 * Accessing DOM elements
 *
 * Another useful application of the useRef() hook is to access DOM elements.
 * This is performed in 3 steps:
 * 
 * - Define the reference to access the element const elementRef = useRef();
 * - Assign the reference to ref attribute of the element: <div ref={elementRef}></div>;
 * - After mounting, elementRef.current points to the DOM element.
 */

import { useRef, useEffect } from 'react';
function AccessingElement() {
  const elementRef = useRef();
   useEffect(() => {
    const divElement = elementRef.current;
    console.log(divElement); // logs <div>I'm an element</div>
  }, []);
  return (
    <div ref={elementRef}>
      I'm an element
    </div>
  );
}
Comment

useref

function TextInputWithFocusButton() {
 const inputEl = useRef(null);
 const onButtonClick = () => {
    inputEl.current.focus();
  };
return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus</button>
    </>
  );
}
Comment

useref example

import { useRef } from "react";

function ExampleUseRef() {
  const inputNode = useRef(null);

  const onClick = () => {
    inputNode.current.focus();
  };

  return (
    <>
      <input ref={inputNode} type="text" />
      <button onClick={onClick}>Focus..</button>
    </>
  );
}
Comment

useRef

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` 指向已挂载到 DOM 上的文本输入元素
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Comment

what does useref do react

const refContainer = useRef(initialValue);
//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). 
//The returned object will persist for the full lifetime of the component.
Comment

what is useref in react

useRef is an kind of alternative to useState hook , with useRef you can get an reference to  an element and than use the DOM/JS properties to modify it .
You can even call useRef as an tool which is used to apply all the DOM properties as you were doing in Javascript before coming to React.
If you use useRef than this  apparoch is called un-controlled components.
Comment

useref in react

import { useRef } from 'react';

function LogButtonClicks() {
  const countRef = useRef(0);  
  const handle = () => {
    countRef.current++;    console.log(`Clicked ${countRef.current} times`);
  };

  console.log('I rendered!');

  return <button onClick={handle}>Click me</button>;
}
Comment

useRef example

import React, { useRef, useEffect } from 'react';

function CountMyRenders() {
  const countRenderRef = useRef(1);
  
  useEffect(function afterRender() {
    countRenderRef.current++;  });

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

useref

  const inputEl = useRef(null);
Comment

useRef

import { useRef, useState, useEffect } from 'react';
function Stopwatch() {
  const timerIdRef = useRef(0);
  const [count, setCount] = useState(0);
  const startHandler = () => {
    if (timerIdRef.current) { return; }
    timerIdRef.current = setInterval(() => setCount(c => c+1), 1000);
  };
  const stopHandler = () => {
    clearInterval(timerIdRef.current);
    timerIdRef.current = 0;
  };
  useEffect(() => {
    return () => clearInterval(timerIdRef.current);
  }, []);
  return (
    <div>
      <div>Timer: {count}s</div>
      <div>
        <button onClick={startHandler}>Start</button>
        <button onClick={stopHandler}>Stop</button>
      </div>
    </div>
  );
}
Comment

useRef

import { useRef, useState, useEffect } from 'react';
function Stopwatch() {
  const timerIdRef = useRef(0);
  const [count, setCount] = useState(0);
  const startHandler = () => {
    if (timerIdRef.current) { return; }
    timerIdRef.current = setInterval(() => setCount(c => c+1), 1000);
  };
  const stopHandler = () => {
    clearInterval(timerIdRef.current);
    timerIdRef.current = 0;
  };
  useEffect(() => {
    return () => clearInterval(timerIdRef.current);
  }, []);
  return (
    <div>
      <div>Timer: {count}s</div>
      <div>
        <button onClick={startHandler}>Start</button>
        <button onClick={stopHandler}>Stop</button>
      </div>
    </div>
  );
}
Comment

useRef

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript recursion 
Javascript :: sequelize transaction 
Javascript :: vuejs list items from axios 
Javascript :: capitalize text js 
Javascript :: js-cookie 
Javascript :: javascript remove element from array in foreach 
Javascript :: invisible recaptcha google 
Javascript :: wild card select jquery 
Javascript :: react-select-search useSelect hook 
Javascript :: react map array 
Javascript :: mongodb mongoose update delete key 
Javascript :: form serialize object javascript 
Javascript :: react hook will mount 
Javascript :: find number in array js 
Javascript :: how to access variable from another component in angular 
Javascript :: longest string 
Javascript :: trigger keydown event javascript 
Javascript :: difference between single quotes and double quotes in javascript 
Javascript :: nodemailer 
Javascript :: how to check if an element is in array javascript 
Javascript :: javascript promise state 
Javascript :: inch to cm 
Javascript :: Declare and Initialize Arrays in javascript 
Javascript :: how to push array object name javascript 
Javascript :: jsonwebtoken 
Javascript :: how to control where the text cursor on div 
Javascript :: calling javascript from java 
Javascript :: scroll to div bottom 
Javascript :: return value 
Javascript :: foreach await js 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =