Minas Mina Minas Mina - 2 months ago 17
React JSX Question

Get query parameters in React, Typescript

I have a component that looks like this:

class MyView extends React.Component<{}, {}> {
render() {
console.log((this.props as any).params); // prints empty object
return (
<div>Sample</div>
);
}
}


I want to print the URL query params but I get an empty object.
(Yes, I know that I declared {} as Props but if I don't define it, it does not compile).

Is there a way to pass a "default" props object to my component so that I can access
this.props.params
? Or should it be done in a different way in TypeScript?

Answer

You need to define the types for the props and state and then put them instead of the {}.
It's not clear where you want to get the "URL query params", so I'll just take them from the window.location object:

interface MyViewProperties {
    params: string;
}

interface MyViewState {}

class MyView extends React.Component<MyViewProperties, MyViewState> {
    render() {
        console.log(this.props.params); // should print "param1=value1&param2=value2...."
        return (
            <div>Sample</div>
        );
    }
}

ReactDOM.render(<MyView props={ window.location.search.substring(1) } />, document.getElementById("container"));