Languages

React - why and when should I pass props to super() method?

0 points
Asked by:
Dirask Community
5460

What is the difference between super() and super(props)? When should I pass props to the super() method?

1 answer
0 points
Answered by:
Dirask Community
5460

You should pass props to the super() method when you want to access this.props in the constructor.

Here is a simple example:

  • with props
    // ONLINE-RUNNER:browser;
    
    // Note: Uncomment import lines while working with JSX Compiler.
    // import React from 'react';
    // import ReactDOM from 'react-dom';
    
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        console.log(this.props.text); // <------ here you can access to the props
      }
    
      render() {
        return <div></div>;
      }
    }
    
    const App = () => {
      return <MyComponent text="Hello world!" />;
    };
    
    const root = document.querySelector('#root');
    ReactDOM.render(<App />, root );
  • without props
    // ONLINE-RUNNER:browser;
    
    // Note: Uncomment import lines while working with JSX Compiler.
    // import React from 'react';
    // import ReactDOM from 'react-dom';
    
    class MyComponent extends React.Component {
      constructor() {
        super();
        console.log(this.props.text); // <------ here the props are undefined
      }
    
      render() {
        return <div></div>;
      }
    }
    
    const App = () => {
      return <MyComponent text="Hello world!" />;
    };
    
    const root = document.querySelector('#root');
    ReactDOM.render(<App />, root );
0 comments Add comment
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join