Hooks help us to manipulate DOM
Earlier DOM Manipulation was possible with createRef() method of React. But this can be done in class component only. Now, after React v16.8 we can manipulate DOM via the “useRef” hook.
Syntax:
useRef(initial value)
For DOM Manipulation we should initialize useRef with null and store that in any variable. After that where ever we have to use that useRef we will simply write:
ref={variable name in which useRef is stored}
So in the below example, we will manipulate DOM by input field so added ref={myref} in the input field.
After that, we added functionality in a function using “useRef” to show “1000” in that input field and to make the background color yellow of that input field. Then we called that function on a button click.
Example:
Javascript
// Filename - App.js import "./App.css" ; import { useRef } from "react" ; function App() { let myref = useRef( null ); function handleDOM() { myref.current.value = 1000; myref.current.style.backgroundColor = "yellow" ; } return ( <div className= "App" > <header className= "App-header" > <h1 className= "gfg" >w3wiki</h1> <h3 className= "gfghook" > DOM Manipulation in Functional Component</h3> <input type= "text" ref={myref}></input> <button onClick={handleDOM}>Click Here</button> </header> </div> ); } export default App; |
Steps to Run the Application: Run your application using the following command:
npm start
Output:
Explain the new feature of React hooks introduced in React v16.8
React v16.8 is no less than a miracle for all the React developers because this version of React introduced hooks to all of us. Before its release, the developer community was tired of using class components but they still had to use them because the functional component does not provide many features that the class component provides. But after hooks, we can use those features in the functional component that was only accessible with the class component. So we can say after this version i.e. React v16.8, the popularity of the class component was reduced.