Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Setting this.props in constructor...? (not trying to mutate props)

I am not trying to mutate props. I just want to have access to this.props in methods called in the constructor:

constructor(props){
    super(props);

    this.props = props; // CAN I? There is no errors or warnings

    const filtered = this.filterValue(props.value);
    this.state = {
        value: filtered,
    }
}

filterValue(value){
    // here I need this.props.*
}

I know there is few ways to do it e.g. additional argument passed to filterValue, however I want it to be as simple as possible. I think that above code is quite intuitive, the question is: can I do it like this? React will override this.props anyway.

like image 629
cimak Avatar asked Jul 25 '16 11:07

cimak


1 Answers

You can access props using this.props in methods as described in the React.Component documentation:

Instance Properties:

  • props

  • state

If you are curious, you can look at the source code of the ReactComponent constructor.

like image 65
Alik Avatar answered Oct 18 '22 18:10

Alik