Calling component in react - reactjs

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.

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

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 React 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 factory method. It creates an object and returns that. But you never have to worry about it.
It is like worrying about addEventListener. How do you know it actually works? :D
PS: There are no real classes in JS. ES6 classes are just an abstraction and are actually created using functions only.

Related

What is use of 'this' in react component

Thank you for contributing your precious time
I am a beginner to react.js;
The word this gets used in React a lot!
I couldn't figure out, what is the use of 'this' in react component.
I read a few articles but, clarity of concept in my mind didn't well
Why did we need to write 'this'?
class MyName extends React.Component {
get name() {
return 'akash';
}
render() {
return <h1>My name is {this.name}.</h1>;
}
}
this refers to your component/class itself. In other languages you can compare it to self. This is to specify that the variable/function you're trying to access or trying to modify is owned by a class so that when you have a parameter with same name with your class variable, the compiler can identify which one was owned by your class.
In your case, this is your MyComponent class. So if you do this.name you will access to your name function that returns an string
If you are learning react, I will recommend you check his official tutorial https://reactjs.org/tutorial/tutorial.html

Is there a way to access a client side object in React?

I am just starting working with react and I am trying to use a web sdk. With client side code, the library is very easy to use: Add its script to the page header and, when the document is ready, it provides you with an object that has properties, methods and events. My goal would be to have access to that object methods and properties inside react. Is it even possible?
In the code below AddScript will create an object called Stuff on the client side and using the browser dev tools I can confirm that the object exists and it not null. How do I use Staff in React?
export class MyStuff extends Component {
constructor(props) {
super(props);
this.state = {
};
}
async componentDidMount() {
try {
await AddScript();
...
Sorry if I wasted anyone's time with this question:
window.Staff
has the required object.

How to check what additional props were passed into a react component that were not defined?

I'm wondering if it's okay to access the defined PropTypes in the React component class, by using: this["__proto__"]["constructor"]["propTypes"]
For example if I have this component:
class Hello extends React.Component {
static propTypes = {
name: string
};
render() {
console.log(this.props);
console.log(this["__proto__"]["constructor"]["propTypes"]);
return <h1>Hello {this.props.name}!</h1>;
}
}
A use case would be that if I want to check what additional props were passed into the component that were not explicitly defined.
To be clear, the above DOES WORK, it's more a matter of whether or not this is something that should be avoided - I know this is probably a somewhat opinionated question, but I haven't seen it anywhere else so, thought I'd look for some feedback. If it should be avoided is there a better way?
Accessing object prototype directly using __proto__ is not recommended because this property has never been part of the ECMAString standard. Main vendors did implement it and these days it will likely work in all the environments targeted by your React app.
Usual replacement for it is Object.getPrototypeOf() method which you could use same way:
Object.getPrototypeOf(this).constructor.propTypes
But in any case, you can read static properties of the class directly:
render() {
console.log(Hello.propTypes);
return <h1>Hello {this.props.name}!</h1>;
}
Prefer this better.

How "this" got binded in the React component method

I have abstracted my React code here. I have not binded "this" to method A(). That is , in the constructor I didnot do
this.A = this.A.bind(this);
nor used any arrow syntax for binding.
So the compiler cannot know what's the value of this inside A().
Since I have used this.map inside A(), the compiler should have thrown error for this usage. When inspecting the code in Chrome Dev Tools, I found the compiler seems to correctly assign the value of this automatically by var _this2 = this. I couldnt understand the behaviour. Can somebody explain this pls. (I am new to React. Kindly bear if this question sounds silly)
class Test extends React.Component{
constructor(props){
super(props);
this.map = [];
this.state = { a: 1};
}
A(){
// some complex logic
this.map = Complexlogic() ;
}
componentWillMount(){
this.A();
}
}
React has created class constructs partially for this purpose. By design, anything created within a class construct is bound to the object context, as it would in any other language's class.
Why you often see functions being 'bound' inside class constructs is for when they have to be passed outside the class context, but you wish to maintain the context of the object for that function. Such as when you pass a function to a component in the render call.
As for why you see "_this2" - its just a way that react manages several different "this" contexts being available at a given time.

How to re-use a method from one component to the next

I have a component that has grown rather large. I decided to break it up into two components, but have found that the component I have split off needs to utilize a method from the original component.
What is the best way to consume a method from inside of an existing component?
Thanks in advance!
Once upon a time, one would have used mixins to achieve what you are looking to do. Since then, this article came out : https://facebook.github.io/react/blog/2016/07/13/mixins-considered-harmful.html
They are still an option in my opinion but require discipline so that you don't overuse the concept.
Other options for you would be:
a) Bring the desired method up one level. By that I mean you could declare it in the container component and pass it along a props to the 2 childrens.
b) If the method is generic enough, declare it in an utility class that you would import in both components. (using static is an option as well)
c) any other innovative way ;) (just to say that these are not the only options)
Extend your base class with in a Split off version. If you use ES6 it would look something like this:
class Base extends React.Component {
renderText () { return 'Hello'}
render(){
return <span>{this.renderText()}</span>
}
}
class SplitOff extends Base {
render() {
return <span>{`${this.renderText()} World`}</span>
}
}
JSFiddle of the above

Resources