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 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 react class component

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}
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 react class component

 constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
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 :: js check if object key exists 
Javascript :: import file in chrome extension 
Javascript :: react native choose simulator 
Javascript :: call by value and call by reference in javascript 
Javascript :: how add class to ckeditor image 
Javascript :: in if condition how to set alert music in javascript 
Javascript :: ajax post request javascript 
Javascript :: express-jwt 
Javascript :: angular playground online 
Javascript :: chunking array javascript 
Javascript :: localstorage getitem 
Javascript :: flask sqlalchemy json 
Javascript :: app script append two list 
Javascript :: how to protect routes in react router v6 
Javascript :: electron vue printer 
Javascript :: elixir guards 
Javascript :: length of array 
Javascript :: this function 
Javascript :: react native fetch response code 
Javascript :: variables in js class 
Javascript :: count duplicate array javascript 
Javascript :: save js 
Javascript :: ionic not compiling with proxy 
Javascript :: axios.create 
Javascript :: leaflet cdn 
Javascript :: start button js 
Javascript :: mapStateProps 
Javascript :: update head tag metadata vue 
Javascript :: promise.all in javascript 
Javascript :: what is the slice method in javascript 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =