I'm building a React app and I would like to know how I can redirect to a 404 page if when in the onMount method of the component. I don't find any data coming from the api
I have already build the 404 page and route
<Route path="*" element={<NotFoundView />} />
Code:
const getExercice = async () => {
try {
const response = await http.get(`/exercicePost/${id}`);
if (response.status !== 400) {
setExercice(response);
}
} catch {}
};
useEffect(() => {
if (id !== undefined) {
setTitle(id.replaceAll("-", " "));
setTitleSplit(id.split("-"));
}
getExercice();
}, [""]);
if (exercice !== undefined) {
return (
<div className="main-container single-exercice">
<div className="single-exercice-go-back grid grid-cols-3 ">
<ButtonGoBack text="retour" link="../" />
</div>
<div className=" md:grid md:grid-cols-3 gap-4">
<div className="single-exercice-title">
<span className="single-exercice-title-transparent">Exercice</span>
{titlesplit.map((element: string, id: number) => (
<span className="single-exercice-title-full" key={id}>
{element}
</span>
))}
</div>
<ImageWrapper imgUrl="d" alt="d" />
</div>
<div className="single-exercice-description">
<PartFrame title="Description" />
<p>{exercice.description}</p>
</div>
<div className="single-exercice-how-to">
<PartFrame title={"Comment faire le " title} />
<TextList list={exercice.howToRealise} />
</div>
</div>
);
} else {
return <h1>Wrong name</h1>;
}
};
I would like to instead of returning <h1>Wrong name</h1>
redirect the user to the path "*" and not mount the page.
CodePudding user response:
solution 1 : change :
else {
return <h1>Wrong name</h1>;
}
to :
else {
return <NotFoundView />;
}
do not forget to import import NotFoundView from "<path>/NotFoundView ";
Solution 2 :
use the useNavigate
hook in your case :
import { useNavigate } from "react-router-dom";
function Test () {
const navigate = useNavigate();
if (.......) {
return ...........;
} else {
return navigate("*");
}
}