Issue
I have a route in react-router-dom
set up like this:
<Route path="/result/:result" component={ResultsView} audio={audio} speechRecognition={speechRecognition} />
And a component with typed props like this:
interface ResultsViewProps {
audio: HTMLAudioElement;
speechRecognition: Types.SpeechRecognition;
}
interface ResultsViewRouterParams {
result: string;
}
interface ResultsViewState {
...
}
export default class ResultsView extends React.Component<
ResultsViewProps & RouteComponentProps<ResultsViewRouterParams>,
ResultsViewState
> {
...
}
As you can see, I'm getting a :result
parameter from the URL, which I want to pass to ResultsView. At the same time, I also want to pass the custom props audio
and speechRecognition
to the same component. Unfortunately, I'm stuck here. I've just recently migrated this project to TypeScript (from pure JS). Previously the above way worked, now TypeScript obviously complains that "Route" doesn't have those custom props. I've tried several ways to instead of simply passing "ResultsView" as the component to the Route, to pass a component with the custom props included, etc., but all those ways didn't work either.
How would I go about doing that?
Solution
Found a solution. When using react-router-dom v5, it's possible to use the render property instead of component to pass in the props for the child component. In my case, this looks like the following:
<Route
path="/result/:result"
render={(props) => <ResultsView audio={audio} speechRecognition={speechRecognition} {...props} />}
/>
I also simplified the typing of the components props like so:
interface ResultsViewProps extends RouteComponentProps<ResultsViewRouterParams> {
audio: HTMLAudioElement;
speechRecognition: Types.SpeechRecognition;
}
interface ResultsViewRouterParams {
result: string;
}
interface ResultsViewState {
...
}
export default class ResultsView extends React.Component<ResultsViewProps, ResultsViewState> {
...
}
Inside the component, it's then possible to read the param through this.props.match.params.result
.
Answered By - Maximilian Krause
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.