I have a Route: /:question/:id
What I want is if put /:questionName/:idnonsense, the nonsense gets removed automatically.
Say /how_to_do_that/123 is an available route, if /how_to_do_that/123345345345 or /how_to_do_that/123awheofhawoeiha entered in the address bar, it will revise automatically to /how_to_do_that/123. Or if I put /how_to_do_that/12, it will replenish it to /how_to_do_that/123. And redirect to /how_to_do_that/123
How am I able to do that? I am using Routes in React. I tried a whole day to make it....
I tried on youtube, their routes can do that. So https://www.youtube.com/watch?v=1fPWr0d5zBE is an available link, if you try to visit https://www.youtube.com/watch?v=1fPWr0d5zBEAHSOHOWIHFOH, it will be revised to https://www.youtube.com/watch?v=1fPWr0d5zBE and visit that link instead. But if you try to visit https://www.youtube.com/watch?v=1fPWr0d5z, that is a 404 (which I think can be improved by matching the close guess).
Does anybody know how to do that? Thanks a lot.
Well, your youtube example doesn't match what you are asking for in your question (route path params vs queryString params), but I think the answer is the same either way. You want to validate a route path parameter. Handle this in the component with a regular expression.
const regexp123 = /^123$/;
console.log(regexp123.test("123345345345"));
console.log(regexp123.test("123"));
console.log(regexp123.test("12"));
In the component the logic might look like this:
import { generatePath, useParams, useNaviate } from 'react-router-dom';
const regexp123 = /^123$/;
const params = useParams();
const navigate = useNavigate();
useEffect(() => {
const { id } = params;
if (!regexp123.test(id)) {
const target = generatePath(
"/:question/:id",
{
...params,
id: '123',
},
);
navigate(target, { replace: true });
}
}, [navigate, params]);
The gist is that the component needs to validate the path parameters manually and handle accordingly. The same for queryString parameters using the useSearchParams hook.