I was trying to redirect to another page in Remix.run
// app/routes/signup.jsx
import { redirect } from "@remix-run/node";
export default function Signup() {
return (
<>
<h1>Signup to SolveIt</h1>
<button onClick={() => redirect("/login")}>Login</button> // trying to redirect to '/login' route
</>
);
}
But, I’m getting an error in the console everytime which says :
Uncaught TypeError: (0 , import_node.redirect) is not a function
2
Answers
In Remix, redirects are performed on the server inside a
loader
oraction
.Your example looks like it could be handled by a simple
<Link>
Here is how you would do it if you really needed to redirect
Here we post the username and password to the
action
function. We get the form data from the request. We can then verify if the credentials are valid. If so, wethrow redirect('/')
. The redirect function returns a Response with the correct status and headers.If it is invalid, we return an error message to the user with the
json
function. Note how we usedthrow
instead of return for the redirect. This is so we can use type inference in the call touseActionData<typeof action>()
. Remix will infer the return value from the payload ofjson
anddefer
functions.In the UI component, we check for the error with
useActionData()
. Since it only returns a value after an action call (POST), it can also beundefined
. We check ifdata?.formError
has a value and if so render it.In addition to the methods in Kiliman’s answer, there is also the the
useNavigate
hook. Which can also be used for page navigation on the client side.