Using Links To Navigate#
Links are used to navigate between pages in React Router.
This will make sure the browser doesn't do a full refresh, but just changes the route.
We will add a link to the FaqItem
component so that we can go to the FaqItemView
view.
4import { Link } from "react-router-dom";
74<Link to={`/faq/${props.index}`}>View</Link>
The full listing of the FaqItem
component is as follows:
1import { useState } from "react";
2import { useDispatch } from "react-redux";
3import PropTypes from "prop-types";
4import { Link } from "react-router-dom";
5
6import { editFaqItem, deleteFaqItem } from "../actions";
7import "./FaqItem.css";
8
9const FaqItem = (props) => {
10 const [isAnswer, setAnswer] = useState(false);
11 const [isEditMode, setIsEditMode] = useState(false);
12 const [question, setQuestion] = useState("");
13 const [answer, setQuestionAnswer] = useState("");
14 const dispatch = useDispatch();
15
16 const toggle = () => {
17 setAnswer(!isAnswer);
18 };
19 const ondelete = () => {
20 dispatch(deleteFaqItem(props.index));
21 };
22
23 const onEdit = () => {
24 setIsEditMode(true);
25 setQuestionAnswer(props.answer);
26 setQuestion(props.question);
27 };
28
29 const onChangeAnswer = (e) => {
30 setQuestionAnswer(e.target.value);
31 };
32 const onChangeQuestion = (e) => {
33 setQuestion(e.target.value);
34 };
35
36 const onSave = (e) => {
37 e.preventDefault();
38 setIsEditMode(false);
39 dispatch(editFaqItem(props.index, question, answer));
40 };
41
42 return (
43 <>
44 {isEditMode ? (
45 <li className="faq-item">
46 <form onSubmit={onSave}>
47 <label>
48 Question:
49 <input
50 name="question"
51 value={question}
52 onChange={onChangeQuestion}
53 />
54 </label>
55 <label>
56 Answer:
57 <textarea
58 name="answer"
59 value={answer}
60 onChange={onChangeAnswer}
61 />
62 </label>
63 <input type="submit" value="Save" />
64 </form>
65 </li>
66 ) : (
67 <li className="faq-item">
68 <h2 className="question" onClick={toggle}>
69 {props.question}
70 </h2>
71 {isAnswer && <p>{props.answer}</p>}
72 <button onClick={ondelete}>Delete</button>
73 <button onClick={onEdit}>Edit</button>
74 <Link to={`/faq/${props.index}`}>View</Link>
75 </li>
76 )}
77 </>
78 );
79};
80
81FaqItem.propTypes = {
82 question: PropTypes.string.isRequired,
83 answer: PropTypes.string.isRequired,
84 index: PropTypes.number.isRequired,
85};
86
87export default FaqItem;
Differences
--- a/src/components/FaqItem.jsx
+++ b/src/components/FaqItem.jsx
@@ -1,6 +1,7 @@
import { useState } from "react";
import { useDispatch } from "react-redux";
import PropTypes from "prop-types";
+import { Link } from "react-router-dom";
import { editFaqItem, deleteFaqItem } from "../actions";
import "./FaqItem.css";
@@ -70,6 +71,7 @@ const FaqItem = (props) => {
{isAnswer && <p>{props.answer}</p>}
<button onClick={ondelete}>Delete</button>
<button onClick={onEdit}>Edit</button>
+ <Link to={`/faq/${props.index}`}>View</Link>
</li>
)}
</>