What would be the correct approach to reading URI parameters from a functional React component?
In JavaScript, if the component is a direct child of a Switch
, we could do:
function MyComponent(props) {
const query = props.location.search;
// ...
}
If the component is not a direct child of a Switch
, we could use a class:
class MyComponent extends Component<RouteComponentProps> {
render() {
const query = this.props.location.search;
// ...
}
}
export default withRouter(MyComponent);
What about a functional component in strict TypeScript?
We want the location
property (and any other, if there are more) to be available and predefined by some interface
or type
, but supplied by React, not the user of the component. An ugly hack would be to define the interface ourselves and then expect it to actually be that way.
If you wrap your component (functional or class) in withRouter, your props extend the RouteComponentProps from react-router, which can be corretly set up, just as you did in the seconds example. To access the correct params, you have to extend the props like this:
RouteComponentProps<{ id?: string; }>
This will let typescript know, that you have a match props with an field id, which is optional. You can now access them type safe with props.match.params.id. You can also extend that, to fit your other parameters. Hope this helps. Happy coding.