In a react component class where exactly is the "props" object being pulled from?

Viewed 68

To get straight to the point, in a react class based component where does the prop object come from?

I am following the official React tic-tac-toe game tutorial.

Firstly, when I take a look at the code for the react Component class (which we extend when creating a React component) I observe that the function has 3 parameters Component(props, context, updater) but I am puzzled as to why in the cases where super() is called only props is passed like so super(props). Shouldn't there be values passed for context and updater also? Why is it that there are no errors when the code is run without super being called?

import React, { Component } from "react";

export class Square extends Component
{
    render()
    {
        return (
            <span>
                <button className="square" onClick={ () => { alert("click") } }>
                    {this.props.value}
                </button>
            </span>
        )
    }
}

To be clear, I understand that the value property in {this.props.value} comes from the property passed to Square <Square value={index}/>; which is a child in another component (Board in the case of the React tutorial) but this is not what I'am referring to.

2 Answers

Props are the properties that are passed from the Super class to the class you create using extends Components in React.

Similar to what happens in OOPS where the parent class properties are passed to the children in the constructor . similar way the props are passed in React this applies in case of functional components too

Note - Please do not confuse it with OOPS concepts [ just to give a Oversimplified version]

One thing is necessary: the parent's (which is Component class) constructor must be invoked within any React class component.

What super does (inside Square's constructor) is to invoke Component's constructor with Square's props. (Hope it's not complicated)

  1. If Square has a constructor then you should call super implicitly.

  2. If Square doesn't have a constructor, then Component's constructor will automatically be invoked when using <Square />.

Also you don't use context or updater directly in your components. So there is no need to define them there.

Related