locked
What is the difference between passing arguments in methods in class-based components and functional components? RRS feed

  • Question

  • User172056746 posted

    Hello,

    What is the difference between passing arguments in methods in class-based components and functional components?

    regards,

    Saeed

    Wednesday, May 19, 2021 9:28 PM

Answers

  • User-474980206 posted

    your question is not clear. but I assume you mean props

      <MyCompoent arg1="foo" arg2="bar" />

    in a function component they are passed to the function, which should return a JSX object.

    // standard syntax
    const MyCompoent = (props) => <pre>
          arg1 = {props.arg1}
          arg2 = {props.arg2}
    </pre>;
    
    // deconstructor syntax
    const MyCompoent = ({arg1, arg2}) => <pre>
          arg1 = {arg1}
          arg2 = {arg2}
    </pre>;

    in a class component props are passed to the constructor. for convience, "this" is bound to object when render is called:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props); // set this.props = props;
      }
      render() {
        return <pre>
             arg1 = {this.props.arg1}
             arg2 = {this.props.arg2}
        </pre>;
      }
    }

    note: with a class object a parent render may force a rerender. if the component is "mounted", then the constructor is not called (as the object exists), but rather the props property is updated, and render is called (along with other lifecycle events). there is never a guarantee that the props values when render is called, match the props values at construction. 
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 19, 2021 9:54 PM