I’m encountering an issue where the parameters language, from, and to are all logging as undefined despite configuring the route and using useParams() correctly in my React application. The setup is as follows:
const { language, from, to } = useParams();
<Route
key="/:language/:from/:to"
path="/:language/:from/:to"
element={<Localized handleTarget={handleTarget} handleSource={handleSource} langs={langs} />}
/>
useEffect(() => {
console.log("Params from URL:", { language, from, to });
}, [language, from, to]);
The URL format I’m using is http://127.0.0.1:5173/es/ko/de. Despite this, all three parameters are logging as undefined. I’ve checked the route order, component placement, router configuration, URL format, and router version, but the issue persists.
Can anyone help identify what might be causing the parameters to be undefined in this setup? Any assistance would be greatly appreciated!
I attempted to configure React Router to capture URL parameters (language, from, and to) using the useParams() hook and then log these parameters within a component. My expectation was that the parameters would be correctly captured from the URL and logged as expected. However, despite configuring the route and using useParams() correctly, all three parameters logged as undefined. I verified the route order, component placement, router configuration, URL format, and router version, but the issue persisted.
2
Answers
The useParams hook is being called in the wrong place here. You should be access the url params from inside the component "Localized" that is assigned to this route.
You should call this useEffect inside the "Localized" component something like
you will have app.js file where the routes are configured. and you can create multiple files for other components. this is the basic setup for configuring react application.
In your scenario, I think you have put all the properties in the same file.
you can follow the procedure and you can achieve what you need.hope it helps
In App.js folder
And in Localized.js file (If you didnt have one create one with .js extension)
Try this. it will work