Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React forwardRef with Redux connect

I have a React functional component that is using forwardRef like this:

const wrapper = React.forwardRef((props, ref) => (
  <MyComponent {...props} innerRef={ref} />
));

export default wrapper;

Now I want to pass some state to this component using mapStateToProps with Redux's connect function like this:

export default connect(mapStateToProps, null)(MyComponent);

I tried to combine them in the following way but it didn't work:

const wrapper = React.forwardRef((props, ref) => (
  <MyComponent {...props} innerRef={ref} />
));

export default connect(mapStateToProps, null)(wrapper);

How do I combine these two to get the desired behaviour?

like image 951
darKnight Avatar asked Mar 09 '20 11:03

darKnight


Video Answer


2 Answers

You can use options in connect function.

connect(mapStateToProps, null, null, { forwardRef: true })(wrapper)
like image 186
Amit Chauhan Avatar answered Sep 23 '22 16:09

Amit Chauhan


You can check the option on the connection method in redux: https://react-redux.js.org/api/connect
So the options allow use forwardRef
my code: connect(null,null,null,{forwardRef: true,})(LearnView)
it worked for me

like image 23
Thanh Cao Avatar answered Sep 23 '22 16:09

Thanh Cao