If you are using React and the react-router-dom library, you may have encountered the error message ‘Function components cannot be given refs’. This error occurs when you try to pass a ref to a functional component wrapped in a route component from react-router-dom. In this blog post, we will explore two solutions to avoid this error and continue using react-router-dom with function components.

Solution 1: Using the withRouter Higher-Order Component

The first solution involves using the withRouter higher-order component provided by react-router-dom. This higher-order component wraps your function component and injects the router props into it, allowing you to access the history, location, and match objects.
Here’s an example of how to use withRouter:


import { withRouter } from 'react-router-dom';

const MyComponent = ({ history }) => {
  // Your component logic here
};

export default withRouter(MyComponent);
    

Solution 2: Using the forwardRef Hook

The second solution involves using the forwardRef hook introduced in React 16.3.0. This hook allows you to forward the ref from the parent component to the child component, even if the child component is a functional component.
Here’s an example of how to use forwardRef:


import { forwardRef } from 'react';

const MyComponent = forwardRef((props, ref) => {
  // Your component logic here
});

export default MyComponent;
    

Conclusion

By using either the withRouter higher-order component or the forwardRef hook, you can avoid the ‘Function components cannot be given refs’ error when using react-router-dom with function components. Choose the solution that best fits your project requirements and continue building amazing React applications.