Wrapping a react-router Link in an html button

Jose Rivera picture Jose Rivera · Feb 26, 2017 · Viewed 157.9k times · Source

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.

enter image description here enter image description here

Answer

Naren Yellavula picture Naren Yellavula · Sep 7, 2017

While this will render in a web browser, beware that:
⚠️Nesting an html button in an html a (or vice-versa) is not valid html ⚠️. If you want to keep your html semantic to screen readers, use another approach.

Do wrapping in the reverse way and you get the original button with the Link attached. No CSS changes required.

 <Link to="/dashboard">
     <button type="button">
          Click Me!
     </button>
 </Link>

Here button is HTML button. It is also applicable to the components imported from third party libraries like Semantic-UI-React.

 import { Button } from 'semantic-ui-react'
 ... 
 <Link to="/dashboard">
     <Button style={myStyle}>
        <p>Click Me!</p>
     </Button>
 </Link>