I am having difficulty using ref
s 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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With