5

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.

Michael
  • 169
  • 3
  • 11

4 Answers4

10

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>
    );
};
Ankit Saxena
  • 1,067
  • 1
  • 4
  • 16
Aakash Basnet
  • 134
  • 1
  • 5
7

I think you need to use the component attribute :

 <Button component={Link} to="./Form"
          variant="contained"
          color="secondary"
          >
          CLICK
        </Button>
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Thanks, this is helpful. For I tried the same, "component={Link}" but this did not work. How can i make an onSubmit trigger a change for a ? Is there something I'm missing because I don't see this anywhere in MUI's docs or in React-Router v6's docs. – Michael Jan 04 '22 at 17:14
  • With onsubmit you will have to use a function which calls history.push() inside it. Textfield are not supposed to act like links, hence the functionality is not there. That is why the component attribute is not working – Tushar Shahi Jan 04 '22 at 17:16
  • Ok, thank you so very much. – Michael Jan 04 '22 at 17:32
  • Sure. If it helps you please mark this as the accepted answer(green tick) – Tushar Shahi Jan 04 '22 at 17:32
2

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>
  );
0

Just useLinkClickHandler

const ButtonLink = ({to, children, ...rest}) => {
  const handleClick = useLinkClickHandler(to);

  return (
    <button onClick={handleClick} {...rest}>
      {children}
    </button>
  );
};
Igor Sukharev
  • 2,467
  • 24
  • 21