Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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 in functional component

import React, { 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

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

  const inputEl = useRef(null);
Comment

React useRef Hook

//Use useRef to track application renders
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);

  useEffect(() => {
    count.current = count.current + 1;
  });

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
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 :: convert svg to base64 javascript 
Javascript :: iterate object in react 
Javascript :: javascript change url 
Javascript :: substring javascript 
Javascript :: truncate text javascript 
Javascript :: javascript sum array values 
Javascript :: get number of days between two dates mongodb query 
Javascript :: how remove last letter js 
Javascript :: can you call api in next.js getserverside props 
Javascript :: setting className using useEffect 
Javascript :: users api testing 
Javascript :: find object in array by property javascript 
Javascript :: return response json two variables laravel 
Javascript :: An external JavaScript cannot contain the <script tag 
Javascript :: split url javascript 
Javascript :: vue.js slots 
Javascript :: ternary operator angular template 
Javascript :: react native open gmail app 
Javascript :: sublime format json 
Javascript :: regexp object js 
Javascript :: js validate phone number 
Javascript :: styling element using jquery 
Javascript :: how to merge two sorted arrays in javascript 
Javascript :: merge 2 dictionaries with same keys javascript 
Javascript :: javascript array add 
Javascript :: remove local storage item 
Javascript :: epsilon javascript 
Javascript :: custom attribute jquery selector 
Javascript :: mongoose schema cast decimals 
Javascript :: regular expression to remove underscore from a string javascript 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =