score:245

Accepted answer

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>

score:0

as i searched through answers everyone was talking about the old versions of react-router-dom, so this might be useful answer for those who want to use the hooks in functional components. as in the new version few hooks are changed and even the withrouter is not applicable you need to make a custom hoc.

we can achieve it through functional components you can use your button and then describe onclick event to trigger to the next page through usenavigate hook.

react-router-dom version 6


this is only possible in functional components as i am using hooks, if you want to use on class components then you can make hoc.

import {link, usenavigate} from 'react-router-dom';
function home() {
you can pass your state like so:  navigate('/show',{state});
const toshowinfopage=()=>{
navigate('/show');

  }


return(
<>


 /*you can use button as well or anything 
of your choice, but remember 
you have to pass the onclick event.
    */
 <a 
onclick={()=>{toshowinfopage()}} 
style={{textdecoration:'none',
paddingright:'20px',
color:'#187bcd',
cursor:'pointer'}}>


</>

)



}

to access usenavigate() with a class component you must either convert to a function component, or roll your own custom withrouter higher order component to inject the "route props" like the withrouter hoc from react-router-dom v5.x did.


this is just a general idea. if you want to usenavigate here's an example custom withrouter hoc:

const withrouter = wrappedcomponent => props => {
  const params = useparams();
  // etc... other react-router-dom v6 hooks

  return (
    <wrappedcomponent
      {...props}
      params={params}
      // etc...
    />
  );
};

and decorate the component with the new hoc.

export default withrouter(post);

this will inject a props for the class component.

score:1

many of the solutions have focused on complicating things.

using withrouter is a really long solution for something as simple as a button that links to somewhere else in the app.

if you are going for s.p.a. (single page application), the easiest answer i have found is to use with the button's equivalent classname.

this ensures you are maintaining shared state / context without reloading your entire app as is done with

import { navlink } from 'react-router-dom'; // 14.6k (gzipped: 5.2 k)

// where link.{something} is the imported data
<navlink classname={`bx--btn bx--btn--primary ${link.classname}`} to={link.href} activeclassname={'active'}>
    {link.label}
</navlink>

// simplified version:
<navlink classname={'bx--btn bx--btn--primary'} to={'/mylocalpath'}>
    button without using withrouter
</navlink>

score:1

i recommend that you utilize the component prop on the link component. using this, you can have effectively any component behave as an a component from the perspective of react rotuer. for instance, you can create your own "button" component and then utilize this.


const mybutton = () => {
    return <button>do something with props, etc.</button>
}

<link to="/somewhere" component={mybutton}>potentially pass in text here</link>

score:1

using react-router-dom and a function

in react, you can use react-router-dom by applying the usehistory call...

- firstly

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

- secondly inside your function...write a function to handle the button click

const handlebuttonclick = () => {
    history.push('/yourpagelink')
  }

- lastly

<button onclick={handlebuttonclick} classname="css">
   button text
</button>

score:4

<button component={link} to="/dashboard" type="button">
    click me!
</button>

score:6

with styled components this can be easily achieved

first design a styled button

import styled from "styled-components";
import {link} from "react-router-dom";

const button = styled.button`
  background: white;
  color:red;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid red;
  border-radius: 3px;
`
render(
    <button as={link} to="/home"> text goes here </button>
);

check styled component's home for more

score:7

i use router and < button/>. no < link/>

<button onclick={()=> {this.props.history.replace('/mypage')}}>
   here
</button>

score:7

for anyone looking for a solution using react 16.8+ (hooks) and react router 5:

you can change the route using a button with the following code:

<button onclick={() => props.history.push("path")}>

react router provides some props to your components, including the push() function on history which works pretty much like the < link to='path' > element.

you don't need to wrap your components with the higher order component "withrouter" to get access to those props.

score:13

update for react router version 6:

the various answers here are like a timeline of react-router's evolution 🙂

using the latest hooks from react-router v6, this can now be done easily with the usenavigate hook.

import { usenavigate } from 'react-router-dom'      

function mylinkbutton() {
  const navigate = usenavigate()
  return (
      <button onclick={() => navigate("/home")}>
        go home
      </button>
  );
}

score:25

you can use usehistory hook since react-router v5.1.0.

the usehistory hook gives you access to the history instance that you may use to navigate.

import react from 'react'
import { usehistory } from 'react-router-dom'

export default function somecomponent() {
  const { push } = usehistory()
  ...
  <button
    type="button"
    onclick={() => push('/some-link')}
  >
    some link
  </button>
  ...
}

note: be aware that this approach answers the question but is not accessible like @ziz194 says in their comment

this is not accessible though, as the button will not be a tag and thus it doesn't have link behaviours, like opening the link in a new page. it is also not optimal for screen readers.

conclusion: the better way to handle this is to use an <a> tag and style it.

score:35

if you are using react-router-dom and material-ui you can use ...

import { link } from 'react-router-dom'
import button from '@material-ui/core/button';

<button component={link} to="/open-collective">
  link
</button>

you can read more here.

score:52

why not just decorate link tag with the same css as a button.

<link 
 classname="btn btn-pink"
 role="button"
 to="/"
 onclick={this.handleclick()}
> 
 button1
</link>

score:141

linkbutton component - a solution for react router v4

first, 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 router link component (or vice-versa) will render in a web browser, but it is not semantic, accessible, or valid html:

<a stuff-here><button>label text</button></a>
<button><a stuff-here>label text</a></button>

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…

<button>label text</button>

…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 component

here’s a linkbutton component for you to copy/pasta:

// file: /components/linkbutton.jsx
import react from 'react'
import proptypes from 'prop-types'
import { withrouter } from 'react-router'

const linkbutton = (props) => {
  const {
    history,
    location,
    match,
    staticcontext,
    to,
    onclick,
    // ⬆ filtering out props that `button` doesn’t know what to do with.
    ...rest
  } = props
  return (
    <button
      {...rest} // `children` is just another prop!
      onclick={(event) => {
        onclick && onclick(event)
        history.push(to)
      }}
    />
  )
}

linkbutton.proptypes = {
  to: proptypes.string.isrequired,
  children: proptypes.node.isrequired
}

export default withrouter(linkbutton)

then import the component:

import linkbutton from '/components/linkbutton'

use the component:

<linkbutton to='/path/to/page'>push my buttons!</linkbutton>

if you need an onclick method:

<linkbutton
  to='/path/to/page'
  onclick={(event) => {
    console.log('custom event here!', event)
  }}
>push my buttons!</linkbutton>

update: if you're looking for another fun option made available after the above was written, check out this userouter hook.


Related Query

More Query from same tag