What is use of 'this' in react component - reactjs

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

Related

Calling component in react

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.

Unable to Change attribute in JS Object passed from Parent as API Variable in Lightning Web Component

When I am trying to change the value of an Api attribute in connected callback of my LWC, the value does not change. It retains the value coming from Parent.
Please find example code below:
export default class myLWC extends LightningElement{
#api myApiVar={};//isNew is true in parent
connectedcallback{
Console.log(myApiVar.isNew);//true
myApiVar.isNew=false;
Console.log(myApiVar.isNew);//true
}
=================================================
Please advice if I am missing anything here
Here you are trying to modify a public variable with api decorator which is not possible directly. You need to introduce a new Temp object to solve your purpose.
You can modify your code to change as :
export default class myLWC extends LightningElement{
#api myApiVar={};//isNew is true in parent
connectedcallback{
Console.log(myApiVar.isNew);//true
let tmpObj = JSON.parse(JSON.stringify(myApiVar));
tmpObj.isNew=false;
myApiVar=tmpObj;
Console.log(myApiVar.isNew);//false
}
=================================================
Please mark this as best answer if it works for you.

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