Home > Software engineering >  Calling component in react
Calling component in react

Time:12-27

I am new in react and i come to this new syntax please help me to understand it better.

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }

 render() {
    return <h2>I am a {this.state.color} Car!</h2>;
  }
}

root.render(<Car color="red"/>);

I have created a class component and as in object oriented programing we should create the instance of class to use it but here we are not initiating a class instance we just write the name of class in jsx language.

can anyone help me here what's happening behind the scene.

CodePudding user response:

Actually react take cares of it on its own. We dont need to create instance while using recactjs.

please read the explanation here in offcial doc of reactjs. (There mentioned below sentence.)

"Function components don’t have instances at all. Class components have instances, but you never need to create a component instance directly—React takes care of this."

https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html

CodePudding user response:

React is a library and does it so you don't have to worry about it.

The syntax you just saw is JSX. It is just syntactic sugar for React.CreateElement. And when you go to the source code you can see that a constructor is actually called.

return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );

Here ReactElement is a constructor and an instance is definitely created. But you never have to worry about it. It is like worrying about addEventListener. How do you know it actually works? :D

  • Related