darKnight
darKnight

Reputation: 6481

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?

Upvotes: 27

Views: 14089

Answers (3)

Thanh Cao
Thanh Cao

Reputation: 161

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

Upvotes: 3

Joe Lloyd
Joe Lloyd

Reputation: 22363

If MyComponent is a functional component use hooks

This means that you don't need to write the connect wrapper at all. You can use hooks for redux is you're using a functional component.

const result : any = useSelector(selector : Function, equalityFn? : Function)

and

const dispatch = useDispatch()

Upvotes: -1

Amit Chauhan
Amit Chauhan

Reputation: 6869

You can use options in connect function.

connect(mapStateToProps, null, null, { forwardRef: true })(wrapper)

Upvotes: 38

Related Questions