Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for passing props to super() in a React constructor when props aren't accessed within it?

I've seen many code snippets such as HelloWorld, where props is passed to super(). What is the reason to do that when this.props is not accessed in the constructor?

class HelloWorld extends Component {
    constructor(props) {
        super(props);

        this.state = { message: 'Hi' };
        this.logMessage = this.logMessage.bind(this);
    }

    logMessage() {
        console.log(this.state.message);
    }

    render() {
        return (
            <input type="button" value="Log" onClick={this.logMessage} />
        );
    }
}
like image 421
j.doe Avatar asked Oct 29 '22 05:10

j.doe


1 Answers

The constructor for a React component is called before it is mounted. When implementing the constructor for a React component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Read Here for more details.

like image 171
Gaurav joshi Avatar answered Nov 12 '22 19:11

Gaurav joshi