React ref returns a 'Connect' object instead of a DOM

I am trying to create dynamic links for custom components created using the map function.

class PostsList extends Component {

  constructor(props) {
    super(props);
  }

  componentDidUpdate = () => {
    console.log(this.refs);
  }

  render() {
    let posts = this.props.posts || [];
    return (
        <div ref="test">
          {posts.map((post) => {
            return <Post post={post} key={post.id} ref={post.id}></Post>
          })}
        </div>
    );
  }

}

export default PostsList
Run codeHide result

console.logreturns the correct DOM node for refs.test, but for those in the loop, returns an object Connect. Screenshot

Can someone point me in the right direction?

+4
source share
2 answers

It seems to be Posta connected component, while you really want a wrapped component.

You will need to connect to withRef: true:

connect(null, null, null, { withRef: true })(Post);

then use getWrappedInstance()to get the base connected component:

this.refs[<id>].getWrappedInstance()

docs:

[withRef] (Boolean): true, ref getWrappedInstance(). : false

+15

- ( ref). :

<Post
  ...
  innerRef={(node) => { this.myRef = node; }}
/>

, styled-components emotion

0

Source: https://habr.com/ru/post/1666287/


All Articles