-
Hi, how can I change URL when click to a button?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The best way is to don't use a button and instead use a link import { Link } from "@remix-run/react"
// ...
return <Link to="/a-link">Click me</Link> If for some reason you need a button you can do this import { useNavigate } from "@remix-run/react"
// ...
let navigate = useNavigate()
return <button type="button" onClick={() => navigate("/a-link")}>Click me</button> In my experience, if you find yourself needing to navigate after a button click, most of the time is because you need to do something before the navigation, and most of the time you can move whatever you're doing to an action function in the server, return return a redirect from there and wrap the button in a Form that submits to the action. import { type ActionFunction, redirect } from "@remix-run/node"
import { Form } from "@remix-run/react"
export let action: ActionFunction = async ({ request }) => {
await doSomething()
return redirect("/a-link")
}
export default function Screen() {
return (
<Form method="post>
<button>Click me</button>
</Form>
)
} The only scenario when this may not be possible is when you need to integrate with a third-party library that needs to run only client-side, in that case use the useNavigate hook. |
Beta Was this translation helpful? Give feedback.
The best way is to don't use a button and instead use a link
If for some reason you need a button you can do this
In my experience, if you find yourself needing to navigate after a button click, most of the time is because you need to do something before the navigation, and most of the time you can move whatever you're doing to an action function in the server, return return a redirect from there and wrap the button in a Form that submits…