To redirect to a new page when a button is clicked in a Remix application, you can use the useFetcher hook or a simple button with an onClick handler. Below are two approaches:
Approach 1: Using useFetcher
import { useFetcher } from "@remix-run/react";
function MyButton() {
const fetcher = useFetcher();
const handleClick = () => {
fetcher.load('/new-url'); // Replace with your target URL
};
return (
<fetcher.Form method="post" onSubmit={handleClick}>
<button type="button" onClick={handleClick}>
Go to New Page
</button>
</fetcher.Form>
);
}
Approach 2: Using a Simple Button with useNavigate
If you want a simpler approach without using useFetcher, you can use useNavigate from Remix:
import { useNavigate } from "@remix-run/react";
function MyButton() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/new-url'); // Replace with your target URL
};
return (
<button onClick={handleClick}>
Go to New Page
</button>
);
}
Explanation
Approach 1: useFetcher is useful if you want to perform actions that might need to submit data or trigger a loader.
Approach 2: useNavigate is a straightforward way to navigate to a new URL without needing to submit any data.
Top comments (0)