Navigate Using Redirects#
If we want to navigate programmatically, for example after submitting a form, we have to use a different method.
In this example we will create a back button in the FaqItemView
to return to the overview.
First we will create the button:
21<button onClick={onBack}>Back</button>
Then we will add the handler to handle the back event.
This event will make use of the useHistory
hook provide by the react-router-dom
.
Once you call this hook, it will give you access to the history instance that you may use to navigate.
It has a push method which will push to the new route.
14 const onBack = () => {
15 history.push("/");
16 };
The full listing of our new FaqItemView
will look as follows:
1import { useEffect } from "react";
2import { getFaqItems } from "../actions";
3import { useSelector, useDispatch } from "react-redux";
4import { useParams, useHistory } from "react-router-dom";
5
6const FaqItemView = () => {
7 const { index } = useParams();
8 let history = useHistory();
9 const dispatch = useDispatch();
10 const faqItem = useSelector((state) =>
11 state.faq.length ? state.faq[index] : {}
12 );
13
14 const onBack = () => {
15 history.push("/");
16 };
17
18 useEffect(() => {
19 dispatch(getFaqItems());
20 }, [dispatch]);
21
22 return (
23 <div>
24 <h2 className="question">{faqItem.question}</h2>
25 <p>{faqItem.answer}</p>
26 <button onClick={onBack}>Back</button>
27 </div>
28 );
29};
30
31export default FaqItemView;
Differences
--- a/src/components/FaqItemView.jsx
+++ b/src/components/FaqItemView.jsx
@@ -1,15 +1,20 @@
import { useEffect } from "react";
import { getFaqItems } from "../actions";
import { useSelector, useDispatch } from "react-redux";
-import { useParams } from "react-router-dom";
+import { useParams, useHistory } from "react-router-dom";
const FaqItemView = () => {
const { index } = useParams();
+ let history = useHistory();
const dispatch = useDispatch();
const faqItem = useSelector((state) =>
state.faq.length ? state.faq[index] : {}
);
+ const onBack = () => {
+ history.push("/");
+ };
+
useEffect(() => {
dispatch(getFaqItems());
}, [dispatch]);
@@ -18,6 +23,7 @@ const FaqItemView = () => {
<div>
<h2 className="question">{faqItem.question}</h2>
<p>{faqItem.answer}</p>
+ <button onClick={onBack}>Back</button>
</div>
);
};