I am trying to pass useRef
details from parent component to child component.
It works if child is a basic component as follows.
const Apple = React.forwardRef(({
}, ref) => {
console.log(`Apple ref: ${ref}`); // can print value, ref not null
return (
<div ref={ref}>
{`ref is: ${ref && ref.current}`}
</div>
);
});
export default Apple;
But if I use redux and use compose to wrap the component as follows, the ref ends up as null.
How could I fix this?
import { compose } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
const Apple = React.forwardRef(({
p1,
p2,
p3,
}, ref) => {
console.log(`Apple ref: ${ref}`); // no longer working, ref prints null.
return (
<div ref={ref}>
{`ref is: ${ref && ref.current}`}
</div>
);
});
const mapStateToProps = someFunction({
state: getState,
});
const mapDispatchToProps = {
a: a1,
b: a2,
c: a3,
};
const chainUp = compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps)
);
export default chainUp(Apple);
Generally, you probably should not be using withRouter
or connect
in a modern React application.
Those HOCs are necessary for backwards compatibility with legacy class components, but in a function component you can (and should!) just use useRouter
, useSelector
and useDispatch
.