PROGRAMING/React

[REACT] Focus an input - useRef

donghunl 2024. 3. 7. 05:08
반응형

Focus an input upon a component mounting.

 

useRef: Within React, we normally interact with the virtual DOM. Sometimes we need to interact with the actual DOM, however, and to do so you can use refs.

 

Uppm page load, focus the input.

 

FocusInput.js

import { useEffect, useRef } from 'react'

export default function FocusInput() {
  const focusedInput =  useRef(null)
  useEffect(() => {
    focusedInput.current.focus()
  }, [])
  return (
    <div>
      <label htmlFor='focused-input'>Focus me on page load!</label>
      <input name='focused-input' ref={focusedInput}/>
    </div>
  )
}

 

App.js

import FocusInput from './FocusInput'

function App () {
  return (
    <div className='App'>
      <FocusInput />
    </div>
  )
}

export default App

 

결과 화면

반응형

'PROGRAMING > React' 카테고리의 다른 글

[React] 화살표 함수 (Arrow Functions)  (111) 2024.04.18
[REACT] Simple shopping cart  (1) 2024.03.07
[REACT] Simple calculator - useReducer  (1) 2024.03.07
[REACT] Pixel art - React Context  (0) 2024.03.07
[REACT] Color picker  (0) 2024.03.07