Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'ref' on React Styled Components is not working

Tags:

I am having difficulty using refs with Styled Components. When I try to access them in my class methods like below, I get the following error:

Edit.js:42 Uncaught TypeError: this.....contains is not a function

  constructor(props) {     ....     this.setWrapperRef = this.setWrapperRef.bind(this);     this.handleClickOutside = this.handleClickOutside.bind(this);    } ----------   setWrapperRef = (node) => {     this.wrapperRef = node;   }   handleEdit = (e) => {     e.preventDefault();     this.props.onEdit(this.props.id, this.state.title);   } ---------- <Wrapper onSubmit={this.handleEdit} ref={this.setWrapperRef}>   ... </Wrapper> 

I found the code from this question

What am I doing wrong here?

like image 519
nikjohn Avatar asked Jun 12 '18 15:06

nikjohn


People also ask

Can we use ref on React component?

In order to get a reference to a React component, you can either use this to get the current React component, or you can use a ref to get a reference to a component you own. They work like this: var MyComponent = React.

Why ref is not recommended in React?

We should not use ref attribute on function components because they do not have instances. React will assign the current property with Dom element when component mount and assign null to it when component unmount. ref updates happen before componentDidMount or componentDidUpdate methods.

Why we may not use the ref attribute?

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . You may not use the ref attribute on function components because they don't have instances.

What can I use instead of REF IN React?

In react, there is another way to use refs that is called "callback refs" and it gives more control when the refs are set and unset. Instead of creating refs by createRef() method, React allows a way to create refs by passing a callback function to the ref attribute of a component.


1 Answers

I found the answer myself. The solution is to use innerRef instead of ref as the ref itself points to the Styled Component and not the DOM node.

A detailed discussion can be found on GitHub

like image 200
nikjohn Avatar answered Oct 16 '22 10:10

nikjohn