score:245
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.
Source: stackoverflow.com
Related Query
- Wrapping a react-router Link in an html button
- ReactJS: Go to anchor link in HTML with react router dom
- React router Link to conditionally render button
- How to add Link from react router dom to the submit button with the default Submit validation
- React Router issue. Whenever login button is clicked. I am directed to a blank page with the homepage link appended to the login page link is made
- material-ui button with styled-components including react router Link
- ReactJS: Go to anchor link in HTML with react router dom only after the full page load
- React Router Link not rendering as clickable button
- react router link with material ui button submit
- Wrapping a react-router Link in an html button as a submit option
- React router url changes correctly but component not being rendered from button component link
- How to navigate on path by button click in react router v4?
- Pass object through Link in react router
- Open link in new tab in react router programmatically
- React Router work on reload, but not when clicking on a link
- History.push a link to a new tab with react router
- How to pass params into link using React router v6?
- In react router v4 how does one link to a fragment identifier?
- react router relative link does not link properly
- React router Link not causing component to update within nested routes
- Can I use react router Link with CardActionArea?
- Handle back button with react router
- Why is state undefined when passed through React Router Link Component?
- React router browser back button isn't working
- React router Link absolute path
- React Router browserHistory.push open link in a new tab
- React Router doesn`t load external html files
- Need to navigate link while clicking material ui table row in React Router 4
- React Router redirect hash link
- React Router - How to Determine If Back button was hit?
More Query from same tag
- Cypress doesn't type date
- Disable submit button if field is empty
- React Router JWT protect routes
- How to pass the dynamic state and setState to function typescript
- Programatically setting route params in React-Router V4 ends up in 'Page not found'
- React update input value on button click
- ReactJS Router not rendering component
- Redux: conditioning action on state
- How to set value in input field to empty by click on a button in react js?
- React JS - Error - Expected an assignment or function call and instead saw an expression no-unused-expressions
- How to render a string with JSX in React
- How to pass this.props.children using hooks in react
- sort floating numbers in javascript
- Open Google search screen with a word in it React js
- How to show hide Summary Value and display FilterSummary Value when filter
- How To Show Data From A Nested Array Using Mongoose Filter?
- What's Relay operation name?
- Jest & Enzyme. Find amount of all elements inside wrapper
- is fetch() data from API and get() data from API the same?
- React/Typescript : this.setState is not a function
- What is proper way to detect device in Next.js SSR?
- how to receive message from BackgroundJS and change state in ReactJS and Chrome extension?
- React: npm command to create a new component?
- React | Virtual DOM element click event not triggering
- Attach event listener on geolocation permission granted
- React array mapping, toggles all drop-downs on click, I want to open the dropdown for the clicked card only
- REact js noob here, how do you change state object values while looping thru an array with their keys in it
- React + TypeScript usage of className prop
- Super expression must either be null or a function (Custom Marker)
- Overriding TextField color in MaterialUI