Using suggested method: This is the result: A link in the button, Code in between comment lines
I was wondering if there is a way to wrap a Link
element from 'react-router'
in an HTML button
tag using react.
I currently have Link
components to navigate pages in my app, but I would like to map that functionality to my HTML buttons.
LinkButton
component - a solution for React Router v4First, a note about many other answers to this question.
⚠️ Nesting
<button>
and<a>
is not valid html. ⚠️Any answer here which suggests nesting a html
button
in a React RouterLink
component (or vice-versa) will render in a web browser, but it is not semantic, accessible, or valid html:☝Click to validate this markup with validator.w3.org ☝
This can lead to layout/styling issues as buttons are not typically placed inside links.
Using an html
<button>
tag with React Router<Link>
component.If you only want an html
button
tag……then, here's the right way to get a button that works like React Router’s
Link
component…Use React Router’s withRouter HOC to pass these props to your component:
history
location
match
staticContext
LinkButton
componentHere’s a
LinkButton
component for you to copy/pasta:Then import the component:
Use the component:
If you need an onClick method:
If you are using
react-router-dom
andmaterial-ui
you can use ...You can read more here.
Why not just decorate link tag with the same css as a button.
With styled components this can be easily achieved
First Design a styled button
check styled component's home for more
I use Router and < Button/>. No < Link/>
Yes.
You can do something like this:
and then use
<WrappedLink />
instead of<Link />
.While this will render in a web browser, beware that:
⚠️Nesting an html
button
in an htmla
(or vice-versa) is not valid html