Docsity

Redirect - React Router DOM, Resumos de Atualidades

Toggle sidebar
bg1
Because
you
can
return
or
throw
responses
in
loaders
and
actions,
you
can
use
redirect
to
redirect
to
another
route.
It's
really
just
a
shortcut
for
this:
It's
recommended
to
use
redirect
in
loaders
and
actions
rather
than
useNavigate
in
your
components
when
the
redirect
is
in
response
to
data.
See
also:
Returning
Responses
from
Loaders
redirect
1
import
{
redirect
}
from
"
react
-
router
-
dom
";
2
3
const loader
=
async
()
=>
{
4
const user
=
await getUser
();
5
if
(!
user
)
{
6
return redirect
("/
login
");
7
}
8
return null
;
9};
1
new Response
("",
{
2
status
:
302,
3
headers
:
{
4
Location
:
someUrl
,
5
},
6});
Type
Declaration
1
type RedirectFunction
=
(
2
url
:
string
,
redirect
main
pf2

Pré-visualização parcial do texto

Baixe Redirect - React Router DOM e outras Resumos em PDF para Atualidades, somente na Docsity!

Because you can return or throw responses in loaders and actions, you can use redirect

to redirect to another route.

It's really just a shortcut for this:

It's recommended to use redirect in loaders and actions rather than useNavigate in

your components when the redirect is in response to data.

See also:

Returning Responses from Loaders

redirect

1 import { redirect } from "react-router-dom"; 2 3 const loader = async () => { 4 const user = await getUser(); 5 if (!user) { 6 return redirect("/login"); 7 } 8 return null; 9 };

1 new Response("", { 2 status: 302 , 3 headers: { 4 Location: someUrl, 5 }, 6 });

Type Declaration

1 type RedirectFunction = ( 2 url: string,

redirect

main

The URL to redirect to.

The Response options to be used in the response.

© Remix Software, Inc. Brand Docs and examples CC 4.

Edit

3 init?: number | ResponseInit 4 ) => Response;

url

1 redirect("/login");

init