A ref is a state object that holds a value in its current property for the entire lifetime of the component.
An class component example that will show you how to read the value of an input element.
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.input = React.createRef();
console.log("At its creation, the ref.current value is "+this.input.current);
}
handleClick(event) {
console.log('The ref gives access to the HTML element via current: ' + this.input.current.__proto__.toString());
console.log('where you have access to all HTML attribute such as the value');
console.log('Example: the value submitted was: ' + this.input.current.value);
event.preventDefault();
}
render() {
return (
<div>
<label>
Name:
<input type="text" ref={this.input} defaultValue="ChangeMe" />
</label>
<button onClick={this.handleClick}>Read the value</button>
</div>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
<div id="root"></div>
Note that in React, you define the default value with the attribute defaultValue and not value.
Referencing a value that will persist and stay the same on the next renders (React component or React HTML element) to be able to manipulate them.
Avoiding new initialization of value or function. React performs the initialization of the ref value once and ignores it on the next renders.
A Parent component can set a reference on one more child React elements.
Note that once a component unmounts, React:
Due to the DOM manipulation, you can:
Example: In this example:
const Input = function() {
const input = React.useRef();
React.useEffect(function(){
console.log('The DOM element is a '+ input.current.__proto__.toString());
const newValue = "Use Effect Value";
console.log('We can change its value to ('+newValue+') via the DOM element');
input.current.value = newValue;
},[input])
return (
<input type="text" ref={input} value="first Render value"/>
);
}
Refs are created using:
Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
Refs are attached to React elements via the ref attribute.
Something like that:
const ref = React.createRef();
return (
<input type="text" ref={ref} defaultValue="ChangeMe" />
)