2

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?

1
  • How do you render this component? Are you passing this param property to it? Commented Oct 6, 2016 at 23:00

2 Answers 2

3

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

That was it. Thanks!
1

To assign default properties to a component you should use defaultProps:

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

MyView.propTypes = {
  url: React.PropTypes.string
}

MyView.defaultProps = {
  url: ''
}

Check the official docs for more information.

1 Comment

This does not work for TypeScript. propTypes and defaultProps cannot be "seen" by the compiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.