4 years ago
Zaid Bin Khalid
2,519 Views
3
In this session, we will learn about React JS ref with examples and codes.
React JS-Refs.
The method is used to return a reference to the elements is called ref. Mostly cases the ref’s method is avoided. However, refs are useful when we need DOM measurements or to add methods to the components. Although the Refs should be avoided in most cases but it’s also conductive during DOM measurements.
Using Refs.
Now in the provided example, you can see how to use refs that clear the input field. Hence, with the help of the ClearInput function the search for an element with ref=”myInput” value, reset the state. Also, adds focus to it after clicking the button.
//App.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ''
}
this.updateState = this.updateState.bind(this);
this.clearInput = this.clearInput.bind(this);
};
updateState(e) {
this.setState({data: e.target.value});
}
clearInput() {
this.setState({data: ''});
ReactDOM.findDOMNode(this.refs.myInput).focus();
}
render() {
return (
<div>
<input value = {this.state.data} onChange = {this.updateState}
ref = "myInput"></input>
<button onClick = {this.clearInput}>CLEAR</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
export default App;
The main.js file code is given below.
//main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
Once the button is clicked, the input will be cleared and focused.
Where refs can be attached.
Interestingly, Refs are considered as very extensible and can be attached to DOM elements as well as React Class components, though they can’t be attached to functional components as well. The ref’s data and functionalities depending upon where we attach the ref.
With the help of Refs, a DOM element gives us access to its attributes. With the help of Refs, a class component gives us access to that component’s props, state, methods, and it’s an entire prototype.
In myRef will not be recognized and will cause an error because in React currently, we cannot attach refs to functional components as shown in the following example:
// this will fail and throw an errorfunction FunctionComponent() {
return <input />;
}class Parent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return (
<FunctionComponent ref={this.myRef} />
);
}
}
If this scenario occurs your app will not able to compile, ensure the error will not leak into a final build.
4 years ago
Zaid Bin Khalid
2,519 Views
3