Wrapping a react-router Link in an HTML button
Linking together a Link from react-router-dom and a button can be as simple as assigning button-like styles to the Link directly.
Voila! You now have a Link styled as a button.
Going deeper: control & semantics
Navigation via useHistory
For programmatic navigation while maintaining the button-like design, a combination of a React button and the useHistory hook can be quite handy!
By employing the push method, navigation becomes a controllable event, which opens up new possibilities like conditional routing or analytics tracking.
Accessibility first
Maintaining good accessibility standards is crucial. Use semantic HTML and proper ARIA roles to aid users using assistive tech:
Component based approach
The almighty LinkButton component
If you frequently require this functionality, consider creating a reusable LinkButton component:
With LinkButton, you've got semantic consistency and a cleaner codebase all in one reusable unit!
How about the style?
Who are you wearing?
With the Link acting as a button, using consistent styling throughout your application becomes a cakewalk:
Designer wear: Material-UI
When you're leaning towards libraries like Material-UI, set the component prop as Link. Presto! A perfect combination of react-router and Material-UI!
Practical advice
Mind your HTML
While wrapping a Link within a button does give the appearance of a button, consider the implications to accessibility and usability. Use tools like validator.w3.org to ensure valid HTML.
Try using a hook
If you lean towards functional components, useRouter offers a much leaner hook-based approach for easy access to routing functions.
The prop filter
While creating a custom LinkButton component, filter out non-button props for a clean button component:
Was this article helpful?