Ashish Kamble
What is the use of refs?
By Ashish Kamble in React on May 14 2019
  • Dipendra Shekhawat
    Aug, 2019 1

    Refs provide way to access react elements created in the render() method.

    In typical react dataflow, we generally pass information/data from parent to child components using props.

    However, there are cases when we need to modify the child component outside the typical dataflow. So we could use Refs for these cases.

    Creating Refs:

    1. class InLineEdit extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.myRef = React.createRef();
    5. }
    6. render() {
    7. return <div ref={this.myRef} ></div>;
    8. }
    9. }

    Accessing Refs:

    const ref = this.myRef.current;

    Being said that Refs should be avoided and we should do things in a React way i.e props.

    • 2
  • Ashish Kamble
    May, 2019 14

    The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when we need direct access to DOM element or an instance of a component.

    • 1


Most Popular Job Functions


MOST LIKED QUESTIONS