in react bind what does 'this' refer to? [duplicate] - javascript

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
In the following example I'm trying to better understand the bind method. Specifically, what do the two instances of 'this' refer to and why do we need the second one? Also, why don't I need to include 'this' in the callback:
UPDATE:
I understand now that they both refer to FontChooser but why do we want to bind FontChooser.checkbox to FontChooser? Isn't that redundant? or in other words if 'this' refers to the class why do we need to bind a class callback (this.checkbox) to the class (this.checkbox.bind(this))?
It's almost like we are binding a specific instance back to the class callback but (a) where are we creating the specific instance and (b) shouldn't the specific instance already have the class callback
class FontChooser extends React.Component {
constructor(props) {
super(props);
this.state = {
hidden: true,
checked: this.props.bold ? true : false
};
}
displayButtons() {
this.setState({
hidden: !this.state.hidden
});
}
checkbox() {
//why not checkbox(this){
this.setState({ checked: !this.state.checked });
}
render() {
console.log(this.state);
var weight = this.state.checked ? "bold" : "normal";
return (
<div>
<input
type="checkbox"
id="boldCheckbox"
hidden={this.state.hidden}
checked={this.state.checked}
onChange={this.checkbox.bind(this)}
/>
<button id="decreaseButton" hidden={this.state.hidden}>
{" "}
-{" "}
</button>
<span id="fontSizeSpan" hidden={this.state.hidden}>
{" "}
{this.state.size}
</span>
<button id="increaseButton" hidden={this.state.hidden}>
{" "}
+{" "}
</button>
<span
id="textSpan"
style={{ fontWeight: weight, fontSize: this.state.size }}
onClick={this.displayButtons.bind(this)}
>
{" "}
{this.props.text}
</span>
</div>
);
}
}

In javascript, the this keyword points to a different object depending on the context it was executed in. When using a function in the JSX 'template', the function is not executed within your class, but in some other context in React. As a consequence, whatever this refers to, is changed.
One was to work around this, is using the bind() method. This method will replace whatever function it is used on, and replace whatever the this keyword points to, to a new location you provided.
In your example, you're using this.displayButtons.bind(this). Here, this refers to this class (FontChooser), and will make sure that this will point to that class regardless of the execution context.
Take a look at the MDN documentation, there are also easy to understand examples.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Related

Using Javascript to create html custom Tag

class Headers extends React.Component {
render() {
const selected = this.props.selectedPane;
const headers = this.props.panes.map((pane, index) => {
const title = pane.title;
const klass = index === selected ? 'active' : '';
return (
<li
key={index}
className={klass}
onClick={() => this.props.onTabChosen(index)}>
{title}{' '}
</li>
);
});
return (
<ul className='tab-header'>
{headers}
</ul>
);
}
}
export default class Tabs extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedPane: 0
};
this.selectTab = this.selectTab.bind(this);
}
selectTab(num) {
this.setState({selectedPane: num});
}
render() {
const pane = this.props.panes[this.state.selectedPane];
return (
<div>
<h1>Tabs</h1>
<div className='tabs'>
<Headers
selectedPane={this.state.selectedPane}
//onTabChosen={this.selectTab}
panes={this.props.panes}>
</Headers>
<div className='tab-content'>
<article>
hellooooo
{pane.content}
</article>
</div>
</div>
</div>
);
}
}
I'm currently creating a 3 tab section where if you click on a tab, it gives you a new pane.
When looking at the render function I see a custom tag called Headers.
I know it coming from the Headers class at the beginning, but how does that format work? Is that a custom tag we building?
Also when looking at its properties such as onTabChosen, when it is deleted in the render method (for learning purposes) and I click on a selected tab, an error comes up saying
"_this.props.onTabChosen is not a function".
this.props.onTabChosen(index).. was written in the Headers class but not as a function correct?
I guess because I am also confused on how this.props.onTabChosen(index) works since onTabChosen was never declared anywhere, just input after props.
When looking at the render function I see a custom tag called "Headers".
That is not a custom tag. That is a React Component.
I know it coming from the Headers class at the beginning, but how does that format work?
Headers is either a function or a class (i.e. a constructor function).
The function will be called and the first argument passed to it will be an object with properties and values that match the props on the JSX element.
If you're going to use React then read a tutorial, this is very introductory level stuff for the framework.
It is covered very early on in both the MDN tutorial and the official React tutorial.
I guess because I am also confused on how this.props.onTabChosen(index) works since onTabChosen was never declared anywhere, just input after props.
It was declared, just not in the piece of code you shared.

Binding setState() to a global function only affects one instance of a component

Note: I have edited the question after the changes I have made according to Nicholas Tower's answer.
I have a global function which bound to a component and changes it's state.
I want to build a form builder system. There is a global function named setLabel which is bound to a component named InputBox and changes it's state. This global function is triggered via another component named ModalPanel which controls the editable properties on the bound component InputBox. I have simplified the function and component class for simplicity of this question.
Here is the global function:
function setLabel(postID, attributeName ){
var text = 'example';
if(text !== ''){
this.setState({ [attributeName] : text});
}
}
And here is the component which is bound to the setLabel function. Notice how setLabel function is passed from parent InputBox component to child ModalPanel component function as a property.
class InputBox extends Component{
constructor(props){
super(props);
this.state = {
placeholder : '',
maxlength: '',
type: '',
}
this.setLabel = setLabel.bind(this); // Binding this to the global function.
}
render(){
let elementId = "inputElement-" + this.props.idCounter;
let mainElement = <Form.Control
id = {elementId}
type = {this.state.type}
placeholder = {this.state.placeholder}
maxLength = {this.state.maxlength}
/>
return <Row>
<ModalPanel
handleHide = {this.props.handleHide}
handleShow = {this.props.handleShow}
setLabel = {this.setLabel}
/>
</Row>
}
}
Lastly, below is the ModalPanel component function where the setLabel function is triggered.
function ModalPanel(props){
return(
......................
......................
......................
<Button variant="primary" onClick = {() => props.setLabel()}>Save changes</Button>
......................
......................
......................)
}
setLabel function which is aimed to set the state of InputBox must be triggered when a button is clicked in the ModalPanel component. The problem is, there are multiple rendered <InputBox /> components on the window and when I try to use this functionality, "the state change" only affect the first instance of <InputBox /> component. What I want to do is that, every instance should have their own internal state and setLabel() function should be bound to the specific component from where it is called. So that, this function can be able to set the state of different component instances. How could I do that?
Addition:
Please check the link below to see a gif image showing how my system works wrong. As you can see, even though I choose the third input box element to edit it's properties (in this case, set it's placeholder text), the change is being made to the first one.
Go to gif
Add a this. to the beginning, as in:
this.setLabel = setLabel.bind(this);
Now you're setting a property on the instance of the InputBox. Make sure to refer to it using this.setLabel when you reference it later in the component.
Is setLabel acting on a specific postID? Is the problem that <Button /> of every <ModalPanel /> acting on the same postID? Because you aren't using setLabel correctly inside <ModalPanel />. setLabel takes in 2 arguments and right now your implementation isn't using any. This is your click handler.
onClick = {() => props.setLabel()}
Try console.logging inside setLabel and see what values you're getting when you click on each button
function setLabel(postID, attributeName){
console.log(postID, attributeName)
var text = 'example';
if(text !== ''){
this.setState({ [attributeName] : text});
}
}
Since the React components only updated from props or state changes, you need to pair the global state with a local state to update the component. See the code below in a sandbox environment.
let value = 0;
function updateStuff () {
console.log("this from update", this.name);
value++;
this.setState({name: "Hakan " + value});
}
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
name: 'notchanged',
counter: 1
}
this.localFunc = this.localFunc.bind(this)
updateStuff = updateStuff.bind(this)
}
localFunc(){
let {counter} = this.state;
this.setState({counter: counter + 1});
updateStuff();
}
render () {
return (
<div>
<div>Test 2</div>;
<div>Counter: {this.state.counter}</div>
<div>Name: {this.state.name}</div>
<button onClick={this.localFunc}>Increment</button>
</div>
);
}
}
ReactDOM.render(
<Test/>,
document.getElementById('root')
);
Think, you are using React in incorrect way
The preferred way for me looks like:
Have a dumb/presentational InputBox which accepts label as a property (in props, not in state)
Have a smart/container component which contains state of multiple InputBoxes and passes the correct label into InputBox
If you are trying to implement InputBox PropertyEditor as a separate component - consider adding event bus, shared between them for example via React Context (or even use full flux/redux concept)
Add this to your function calls after binding them or use arrow functions !

seState not working

In my app component below I want to hide a div based on a function I have defined but it brings an error saying
TypeError: Cannot read property 'setState' of undefined
Please what may be wrong
class Apps extends Component {
constructor(props) {
super(props);
// Don't do this!
this.state = { showing: true };
}
render() {
return (
<div>
<div className="container">
<div style={{ display: (this.state.showing ? 'block' : 'none') }}>
A Single Page web application made with react
</div>
</div>
<div className="buttons">
<a href='' onClick={this.onclick} >Login</a>
<br/>
<a href='' >Signup</a>
<br />
<a href='' >Members</a>
</div>
</div>
);
}
onclick(e){
e.preventDefault();
this.setState({showing: false});
}
}
You can use bind or you can just use an arrow ES6 function instead of binding it
onclick = (e) => {
e.preventDefault();
this.setState({ showing: false });
}
You can e.g. bind the function to this in the render method so that this will be what you expect in your onclick method. You can read more about why this is the case in the documentation.
<a href='' onClick={this.onclick.bind(this)}>Login</a>
#Tholle is right. You have to bind your onclick function to current class instance using this. By default this here points to global window obj, which does not have setState function.
Either you bind your function to this, where you are calling it as tholle suggests.
You can also bind it to this in constructor after calling super(props):
this.onclick = this.onclick.bind(this);
this can also be bound implicitly using arrow function like this:
< a href="" onClick={e=>this.onclick(e)} ... ./>
Best practice is to use 2nd option. As using 1st and 3rd options will create new references for the functions each time component renders. However, that's ok to use 1st or 3rd option if you have no problem with memory consumption or creating a small app.
You can use ES6 arrow functions to bind lexical this:
href='' onClick= {(e) => this.onclick(e)}

if else statement in map function reactjs

You don't have to read the whole code, just read the comment in the editQuantity function and in showOrderItem function, specially in the showOrderItem function and my problem is i think just silly, as both of my function are working as they supposed to work,
*editQuantity function supposed to change the state, it changing it, i checked by adding the console line.
*showOrderItem function supposed display the item, he is doing that job as well.
My problem is, i try to add conditional rendering in the showOrderItem function that not working, even though i am able to change the state.
Please read the comment in showOrderItem function, to see where is the problem:
import React from 'react';
export default class ShowOrder extends React.Component{
constructor(props){
super(props);
this.state={
quantityEditing:this.props.orderItems,
}
}
editQuantity(item){
const order=this.state.quantityEditing;
for(var i =0; i<order.length; i++){
if(order[i].item==item){
console.log(order[i].orderQuantityEditing)
order[i].orderQuantityEditing=true;
this.setState({order:this.state.quantityEditing})
console.log(order[i].orderQuantityEditing)
}
}
}
showOrderItem(){
const style = {cursor:'pointer'}
const orderItems=this.state.quantityEditing;
console.log(orderItems)
const orderItem=orderItems.map((item,index)=>
<p>
{orderItems.orderQuantityEditing ? 'some':
<span style={style} onClick={this.editQuantity.bind(this,item.item)}>
//as you can see in here i added conditional rendering, that if orderItems.orderQuantityEditing is true display me some, but that's not working --orderItems.orderQuantityEditing ? 'some'(this part) does not matter how many times i click on property it never display me my string 'some'
{item.quantity}</span>}
<span style={style}> {item.item}</span>
<span style={style}> Q</span>
<span style={style}> N</span>
<span style={style}> X</span>
</p>
);
return orderItem;
}
render(){
return(
<div>
{this.showOrderItem()}
</div>
);
}
}
Instead of
{orderItems.orderQuantityEditing ?
'some'
:
<span style={style} onClick{this.editQuantity.bind(this,item.item)}>
I think you need to write this:
{item.orderQuantityEditing ?
'some'
:
<span style={style} onClick={this.editQuantity.bind(this,item.item)}>
Because you are using map, and item will be each object of array, so you need to use item to access that property. During the for loop, when changing the state you wrote:
order[i].orderQuantityEditing=true;
That it proper, order will be an array and you need to provide the index to access particular object of that.

React - passing ref to sibling

I need to have 2 sibling components, and 1 of them has to have a reference to another - is that possible?
I tried this:
<button ref="btn">ok</button>
<PopupComponent triggerButton={this.refs.btn} />
And even this
<button ref="btn">ok</button>
<PopupComponent getTriggerButton={() => this.refs.btn} />
But I get undefined in both situations. Any ideas?
Note: a parent component will not work for me, because I need to have multiple sets of those, like
<button />
<PopupComponent />
<button />
<PopupComponent />
<button />
<PopupComponent />
NOT like this:
<div>
<button />
<PopupComponent />
</div>
<div>
<button />
<PopupComponent />
</div>
<div>
<button />
<PopupComponent />
</div>
Think this question is best answered by the docs:
If you have not programmed several apps with React, your first
inclination is usually going to be to try to use refs to "make things
happen" in your app. If this is the case, take a moment and think more
critically about where state should be owned in the component
hierarchy. Often, it becomes clear that the proper place to "own" that
state is at a higher level in the hierarchy. Placing the state there
often eliminates any desire to use refs to "make things happen" –
instead, the data flow will usually accomplish your goal.
Not sure exactly what you are trying to do, but my hunch is a parent component and passing props is what you really want here.
I completely agree with the quote Mark McKelvy has provided. What you are trying to achieve is considered an anti-pattern in React.
I'll add that creating a parent component doesn't necessarily means it has to be a direct parent, you can create a parent component further up the chain, in which you can render an array of all your children components together, having the logic to coordinate between all the children (or pairs of children according to your example) sit inside your parent.
I created a rough example of the concept which should do the trick:
class A extends React.Component {
onClick(key) {
alert(this.refs[key].refs.main.innerText);
}
render() {
var children = [];
for (var i = 0; i < 5; i++)
children.push.apply(children, this.renderPair(i));
return (
<div>
{children}
</div>
);
}
renderPair(key) {
return [
<B ref={'B' + key} key={'B' + key} onClick={this.onClick.bind(this, 'C' + key)}/>,
<C ref={'C' + key} key={'C' + key} onClick={this.onClick.bind(this, 'B' + key)}/>
];
}
}
class B extends React.Component {
render() {
return <p ref="main" onClick={this.props.onClick}>B</p>;
}
}
class C extends React.Component {
render() {
return <p ref="main" onClick={this.props.onClick}>C</p>;
}
}
React.render(<A/>, document.getElementById('container'));
And any state you need to save for all your children, you do in the common parent. I really hope this helps.
The following code helps me to setup communication between two siblings. The setup is done in their parent during render() and componentDidMount() calls. Hope it helps.
class App extends React.Component<IAppProps, IAppState> {
private _navigationPanel: NavigationPanel;
private _mapPanel: MapPanel;
constructor() {
super();
this.state = {};
}
// `componentDidMount()` is called by ReactJS after `render()`
componentDidMount() {
// Pass _mapPanel to _navigationPanel
// It will allow _navigationPanel to call _mapPanel directly
this._navigationPanel.setMapPanel(this._mapPanel);
}
render() {
return (
<div id="appDiv" style={divStyle}>
// `ref=` helps to get reference to a child during rendering
<NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
<MapPanel ref={(child) => { this._mapPanel = child; }} />
</div>
);
}
}
special-props
Special Props Warning
Most props on a JSX element are passed on to the component, however, there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.
For instance, attempting to access this.props.key from a component (eg. the render function) is not defined. If you need to access the same value within the child component, you should pass it as a different prop (ex: ). While this may seem redundant, it's important to separate app logic from reconciling hints.

Categories