Friday, November 15, 2024
Google search engine
HomeLanguagesReactJS Refs

ReactJS Refs

In this article, we will discuss about refs in React, how we can create refs and where can refs be used.

What are refs?

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all. They have wide functionality as we can use callbacks with them. 

Creating refs in React

Refs can be created using React.createRef() function and attached it with the React element via the ref attribute. When a component is constructed the Refs are commonly assigned to an instance property so that they can be referenced in the component. 

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myCallRef = React.createRef();
}
render() {
return <div ref={this.myCallRef} />;
}
}

Accessing Refs in React

In React, A reference to the node becomes accessible at the current attribute of the ref when a ref is passed to an element in the render.

const node = this.myCallRef.current;

Now, we are going to see how we can use refs in our code which will help you to understand the use case of refs better.

Example: In this example, we use the target value of event e, for getting the value.  

Javascript




// without refs
class App extends React.Component {
    constructor() {
        super();
        this.state = { sayings: "" };
    }
    update(e) {
        this.setState({ sayings: e.target.value });
    }
    render() {
        return (
            <div>
                Mukul Says <input type="text" onChange={this.update.bind(this)} />
                <br />
                <em>{this.state.sayings}</em>
            </div>
        );
    }
}
ReactDOM.render(< App />, document.getElementById('root'));


Output: 

Example: In this example, we use the refs provided by React, to add a callback function.

Javascript




// using refs
class App extends React.Component {
    constructor() {
        super();
        this.state = { sayings: "" };
    }
    update(e) {
        this.setState({ sayings: this.refs.anything.value });
    }
    render() {
        return (
            <div>
                Mukul Says <input type="text" ref="anything"
                    onChange={this.update.bind(this)} />
                <br />
                <em>{this.state.sayings}</em>
            </div>
        );
    }
}
ReactDOM.render(< App />, document.getElementById('root'));


Output: 

Example: In this example, we use the refs provided by React, to add a callback function

Javascript




// callback used inside ref
class App extends React.Component {
    constructor() {
        super();
        this.state = { sayings: "" };
    }
    update(e) {
        this.setState({ sayings: this.a.value });
    }
    render() {
        return (
            <div>
                Mukul Says <input type="text"
                    ref={(call_back) => { this.a = call_back }} onChange=
                    {this.update.bind(this)} />
                <br />
                <em>{this.state.sayings}</em>
            </div>
        );
    }
}
ReactDOM.render(< App />, document.getElementById('root'));


Output: 

When to use refs

  • Helpful when using third-party libraries.
  • Helpful in animations.
  • Helpful in managing focus, media playback, and text selection.

When not to use refs

  • Should not be used with functional components because they don’t have instances.
  • Not to be used on things that can be done declaratively.
  • When using a library or framework that provides its own methods for managing such as Redux or MobX.

We have discussed this in detail with different methods of How to Create refs in the ReactJS article you can learn more about it.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments