Hello there!
Here in this article, I’m going to explain to you how to use react ref properly and write down a real example of the alive world
so ref is a special attribute of the React. We can add it to any element. It takes a callback function which React will execute immediately.
It uses primarily to set focus on some element but we can use it to get a value of input as well. Suppose we have a task like that: Create a React app that will have two inputs and button and store the data to the array like this
1 2 3 4 |
var PLACES = [ { name: "New York", zip: "10157" }, { name: "Rome", zip: "00123" } ]; |
It is very easy to do with refs. Look at the resolution below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { constructor(props) { super(props) this.state = { PLACES: [] } } handler = () => { this.setState({ PLACES: [ ...(this.state.PLACES), { name: this.refName.value, zip: this.refZip.value } ] }) this.refName.value = '' this.refZip.value = '' this.refName.focus() } render() { const { PLACES } = this.state console.log('PLACES = ', PLACES); return ( <div> <h1>App</h1> <ul> {PLACES.map((e, i) => <li key={i}> {e.name + ' ' + e.zip} </li> )} </ul> Name: <input type="text" ref={input => { this.refName = input}} /> Zip: <input type="text" ref={input => { this.refZip = input}} /> <button onClick={this.handler}>Button</button> </div> ) } } ReactDOM.render( <App />, document.getElementById('root') ) |
there is important two parts
the first how we creating refs
1 2 3 4 |
<input type="text" ref={input => { this.refName = input}} /> |
we use a callback function that will execute immediately. All right and the next how we use in the handler function, look at it, too
1 2 3 |
this.refName.value = '' this.refZip.value = '' this.refName.focus() |
yes, you guess. It is accessible now by this.[name]. So here we are. 🙂
Use ref carefully because it’s a thing that directly manipulates the DOM. Which you think some operations are easier to implement with the ref, boldly do it otherwise use declarative methods