IWProgrammer
IWProgrammer

Reputation: 157

Can somebody explain what makes this code?

I've hot React component which returns input tag. Can you please explain what is going on at the eighth line ref={element => element && (element.onChange = onChange)}? I

import React from 'react';

export default function MyInput({
    onChange,
    ...rest
}) {
    return (
        <input
            {...rest}
            ref={element => element && (element.onChange = onChange)}
        />
    );
}

Upvotes: 0

Views: 74

Answers (2)

Sagi Rika
Sagi Rika

Reputation: 2979

React's ref is used to access the DOM directly, and in general is recommended to use as less as possible. The point of functional refs, and keep in mind that they're deprecated, is to assign the element into a class component's variable. e.g.:

Class MyComponent extends Component {
  constructor(props) {
    super(props);  
    this.inputRef = null;
  }

  ...stuff

  render() {
    ...stuff
    <input ref={element => this.inputRef = element} />
  }
}

Then, you could do something like:

this.inputRef.current.style.color = 'blue';

In your case, there is no need for this. If you want to assign the onChange you get from props, just do this:

<input {...stuff} onChange={onChange} />

Read more about React refs here.

As for element && element.onChange, it's designed to make sure that element exists before accessing it's onChange property. Another way to do it, using optional chaining (only avaliable in react-scripts v3.3 and above), is this:

element?.onChange

Upvotes: 2

Muhammad Usama Rabani
Muhammad Usama Rabani

Reputation: 776

Refs are used to access DOM elements

The value of ref differs depending on the type of node:

  1. When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.
  2. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.

They are used in cases where we want to change the value of a child component, without making use of props and all. But in your case, i think you have no need to use ref because you simply wants to assign onChange that you received from props.

Upvotes: 0

Related Questions