React Router v6, How to place <Link /> into a button and event handler

Viewed 3427

I'm trying something like this:

import Button from '@material-ui/core/Button';
import { Link } from "react-router-dom";

return (
    <div className="App">
      <header className="App-header">
        <Button
          variant="contained"
          color="secondary"
          // THIS HERE:
          onClick={<Link to="./Form"/>}
          >
          CLICK
        </Button>

I need: <Button />, with an onClick, to link me to './Form'. I am trying something like <Button onClick={e => <Link to=".Form"/>} and have tried every variation I can think of to make this work. Please someone help, and thanks.

3 Answers

You can use useNavigate hook from react router dom package.

import { useNavigate } from "react-router-dom";
import {Button} from "@mui/material"

export const TestComponent = () => {
    const navigate = useNavigate();

    return (
        <Button onClick={() => navigate('route here...')}>Click me!</Button>
    );
};

I think you need to use the component attribute :

 <Button component={Link} to="./Form"
          variant="contained"
          color="secondary"
          >
          CLICK
        </Button>

You can do it this way

  const history = useHistory();
  const navigateTo = () => history.push('/componentURL');//eg.history.push('/login');

  return (
   <div>
   <button onClick={navigateTo} type="button" />
   </div>
  );
Related