There are 4 methods for binding event handlers that i know. The first one is by binding within the DOM element in render():
<button onClick = {this.clickHandler.bind(this)}>Event</button>
The second one is using an arrow function within the DOM element in render():
<button onClick = {() => this.clickHandler()}>Event</button>
The third one is by binding within the class constuctor:
constructor(props) {
super(props)
this.state = {
message: "Click"
}
**this.clickHandler = this.clickHandler.bind(this);**
}
render() {
return (
<div>
<div>{this.state.message}</div>
**<button onClick = {this.clickHandler}>Event</button>**
</div>
)
}
The forth way is by changing the class property to an arrow function:
clickHandler = () => {
this.setState({
message: 'Goodbye!'
})
}
So which way is best?
From what I know :-
In 1st case, a newly bound clickHandler will be created on every render of your React app.
In 2nd case, a new anonymous arrow function will be created which internally calls the clickHandler (on-execution) on every render of your React app.
Both 3rd and 4th are better since they cause one-time creation of the clickHandler. They are outside the render flow.
Related
I need to make a hidden button visible when hovering over an adjacent text. This is being done through onMouseEnter and onMouseLeave events.
But when clicking on the text besides, I need to make the button completely visible and stop the onMouseLeave event.
So far what I have tried: trying to remove the onMouseLeave event using removeEventListener.
I know we could do this with the help of a variable like:
const mouseOut = (divId) => {
if (!wasClicked)
document.getElementById(divId).style.visibility = "hidden";
}
But since I have way too may different buttons and text, I do not want to use variables either.
<div className="step-buttons" onMouseEnter={mouseOver.bind(this, 'feature')}
onMouseLeave={mouseOut.bind(this, 'feature')}
onClick={showButtonOnClick.bind(this, 'feature')}>Test Suite
</div>
Is there anything that could help me here?
Any suggestion would be welome,
Thanks in advance :)
Way 1:
You can mount an eventlistener for leaving in the MouseEnter function and remove it in the onClick eventhandling with refs like so:
constructor(props) {
super(props);
this.text;
this.onMouseLeave = this.onMouseLeave.bind(this);
}
onMouseEnter(){
//apply your styles
this.text.addEventListener('mouseleave', this.onMouseLeave);
}
onMouseLeave(){
//remove your styles
}
showButtonOnClick(){
//remove the eventlistener
this.text.removeEventListener('mouseleave', this.onMouseLeave);
}
render(){
return(
<div ref={(thiscomponent) => {this.text = thiscomponent}}
onMouseEnter={this.onMouseEnter.bind(this, 'feature')}
onClick={this.showButtonOnClick.bind(this, 'feature')}>
Test Suite
</div>);
}
The ref ist just a reference for your div, so that you can mount the eventlistener to it.
You have to bind the function in the constructor, as .bind(this) will create a new function when you call it, to prevent mounting the eventhandler multiple times.
Way 2(probably better):
Another method would be to save the click on the text in the state, and conditionaly change what your onMouseLeave function does based on that:
constructor(props) {
super(props);
this.state={
clicked: false,
}
}
onMouseEnter(){
//apply your styles
}
onMouseLeave(){
if(!this.state.clicked){
//remove styles
}
}
showButtonOnClick(){
this.setState({clicked: true});
}
render(){
return(
<div
onMouseEnter={this.onMouseEnter.bind(this)}
onMouseLeave={this.onMouseLeave.bind(this)}
onClick={this.showButtonOnClick.bind(this)}>
Test Suite
</div>);
}
You can use removeEventListener to remove the mouseleave event in your showButtonOnClick function
showButtonOnClick(){
...your function...
document.getElementById('step-button').removeEventListener('mouseleave',this.callback());
}
callback(){
console.log("mouseleave event removed");
}
As you are doing this many times, it seems like creating these as components and using its state to store visibility without creating tons of global variables might be worthwhile.
Have been playing around with react. Have two event listeners the input which listens onChange and the button which should push the value to the array when its clicked.
Here's the code:
import React, { Component } from 'react';
let arr = [];
class App extends Component {
constructor() {
super();
this.state = {text: 'default'}
}
update( e ) {
this.setState({text: e.target.value})
}
add ( value ) {
arr.push(value)
console.log(arr)
}
render() {
return (
<div>
<h1>{this.state.text}</h1>
<input onChange={this.update.bind(this)}/>
<button onClick={this.add(this.state.text)}>Save</button>
</div>
)
}
}
export default App
The problem that the add function is running on change. Can't really get why.
Any suggestions?
onChange() triggers update()
update() calls this.setState() which changes state.
A state change causes render() to be invoked to re-render according to new state.
Rendering <button onClick={this.add(this.state.text)}>Save</button> invokes add() every time render() runs.
In order to defer invoking add(), you can define a function which gets triggered by the click event, as was shown in another answer. Alternatively, you can achieve the same functionality by adding a class method which encapsulates the trigger functionality:
addText() {
this.add(this.state.text)
}
render() {
…
<button onClick={this.addText.bind(this)}>Save</button>
This may or may not work for you, but in the context of the example, given, this would work.
Change <button onClick={this.add(this.state.text)}>Save</button>
To <button onClick={() => this.add(this.state.text)}>Save</button>
In your variant function add firing when component is rendering, and when you call setState with onChange of input you call this re-render.
The problem is add(this.state.text) is called whenever render() is called. To avoid this, you do not need to send the state as parameter, all you need to do is
<button onClick={this.add}>Save</button
or if you want to send a parameter you should bind it
<button onClick={this.add.bind(this, this.state.text)}>Save</button>
When handling events in a (dump) child component in React, what should be supplied to the callback passed from its (smart) parent component to make it as intended? Should it be the event or only the portion of the result that we are interested in? How does it scale when we have deeply nested components? Are there some other considerations?
Intuitively, I see benefits behind passing the whole event because (i) we can get more data from the event when handling it in the parent and (ii) it separates concerns (the dump components only render and have no logic). On the other hand, it requires the child to have a constructor to bind the wrapper method.
I've seen both approaches used. For example, in Thinking in React the author wraps callbacks in the child component to pass values (see the code on CodePen), whereas in most of the SO posts the event is passed and its value is extracted in the parent component via event.target.value.
Code examples
Pass event:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({checked: event.target.checked});
}
render() {
return (
<Child checked={this.state.checked} handleClick={this.handleClick}/>
);
}
}
class Child extends React.Component {
render() {
return (
<p>
<input
type="checkbox"
checked={this.props.checked}
onChange={this.props.handleClick}
/>
{" "}
Click me
</p>
);
}
}
Pass value only (notice handleClick2 ):
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(checked) {
this.setState({checked: checked});
}
render() {
return (
<Child checked={this.state.checked} handleClick={this.handleClick}/>
);
}
}
class Child extends React.Component {
constructor(props) {
super(props);
this.handleClick2 = this.handleClick2.bind(this);
}
handleClick2(event) {
this.props.handleClick(event.target.checked);
}
render() {
return (
<p>
<input
type="checkbox"
checked={this.props.checked}
onChange={this.handleClick2}
/>
{" "}
Click me
</p>
);
}
}
You should pass the thing that you need without the event. There is no need for the whole object unless you want to extract relevant data from the event: for example the target or when you use the same callback for multiple elements/actions.
You won't have any performance problems and there is definitely no react-ish way to do this. Just use your judgement.
event.target is part of the Web Platform standard. For example:
Lets look at an example of how events work in a tree:
<!doctype html>
<html>
<head>
<title>Boring example</title>
</head>
<body>
<p>Hello <span id=x>world</span>!</p>
<script>
function debug(target, currentTarget, eventPhase)
{
console.log("target: " + JSON.stringify(target) );
console.log("currentTarget: " + JSON.stringify(currentTarget) );
console.log("eventPhase: " + JSON.stringify(eventPhase) );
}
function test(e) {
debug(e.target, e.currentTarget, e.eventPhase)
}
document.addEventListener("hey", test, true)
document.body.addEventListener("hey", test)
var ev = new Event("hey", {bubbles:true})
document.getElementById("x").dispatchEvent(ev)
</script>
</body>
</html>
The debug function will be invoked twice. Each time the events's target attribute value will be the span element. The first time currentTarget attribute's value will be the document, the second time the body element. eventPhase attribute's value switches from CAPTURING_PHASE to BUBBLING_PHASE. If an event listener was registered for the span element, eventPhase attribute's value would have been AT_TARGET.
So it would be easy to port to something newer or renewable.
References
W3C DOM4
Accelerated Mobile Pages – A new approach to web performance
Event Handling — Vue.js
AMP Actions and Events: ampproject/amphtml
TypeScript: Using jquery $(this) in event
So, let's say I have a class named Search that is a simple input field with a submit button. Here's the code for that.
class Search extends Component {
constructor(props){
super(props);
this.state = {term: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log(this);
console.log(e.target.value);
this.setState({term: e.target.value});
}
render() {
return (
<form className='input-group'>
<input className='form-control'
placeholder='City'
onChange={this.handleChange}
value={this.state.value}/>
<span className='input-group-btn'>
<button type='submit' className='btn btn-primary'>Submit</button>
</span>
</form>
)
}
}
So, I need to bind the this keyword to the event handler, handleChange, inside the constructor of the class so that it has the correct reference to this inside the handleChange event handler.
However, if I change the code to the following
class Search extends Component {
constructor(props){
super(props);
this.state = {term: ''};
//this.handleChange = this.handleChange.bind(this);
Line comment above
}
handleChange(e) {
console.log(this);
console.log(e.target.value);
this.setState({term: e.target.value});
}
render() {
return (
<form className='input-group'>
<input className='form-control'
placeholder='City'
onChange={(e) => this.handleChange(e)}
Line change above
value={this.state.value}/>
<span className='input-group-btn'>
<button type='submit' className='btn btn-primary'>Submit</button>
</span>
</form>
)
}
}
Now, if I change the code to the above, I no longer need to do that because I am calling this.handleChange from inside of a callback. Why is this the case?
The reason is that you use an arrow function when you create the callback.
You don't need to bind arrow functions to this, because arrow functions "lexically binds the this value".
If you want, you can change your event handler functions into arrow functions, so that you don't need to bind them. You may need to add the babel plugin 'transform-class-properties' to transpile classes with arrow functions.
If you want to change handleChange into an arrow function, simply change
handleChange(e) {
...
}
to
handleChange = (e) => {
...
}
What you have to consider is what you are expectingthis will evaluate to inside a method and this is something that is not just confined to callbacks.
In the the case of your handleChange method you are referring to this.setState where you are expecting this to be the body of your containing class where it is defined when you create a class extending from React.Component.
When a DOM on-event handler like onClick is invoked, the this keyword inside the handler is set to the DOM element on which it was invoked from. See: Event handlers and this on in-line handler.
As you can infer, there is no setState method on a DOM element, so in order to achieve the desired result, binding the this to the correct scope/context is necessary.
This can be achieved with .bind() or the => (arrow function), the latter of which does not define its own its own scope/context and uses the scope/context it is enclosed in.
Like I said previously the redefining of this is not just confined to DOM on-event callbacks. Another example is when you call the .map() method where you can define the context of this by passing in a context value as a second argument.
I have a button with an onClick event that sends a value to my state and should remove it from the state on a second click:
<button
type="button"
value={posts.index}
onClick={this.props.data ? this.props.remove : this.props.add}
key={cont._id}
data={-1}
>
My problem is that I dunno how to set the data attribute to 1 after the first click, so the second click would fire the remove function. How do I achieve that?
action creator
export function add(e) {
return{
type: ADD,
payload: e.target.value
}
}
Set the value before the return.
render() {
const buttonAction = this.props.data ? this.props.remove : this.props.add
return (
<button
type="button"
value={posts.index}
onClick={buttonAction}
key={cont._id}
data={this.props.data}>
)
}
I'm assuming the data attribute in prop contains the value you want the data attribute to contain.
First, ensure that in the parent component, data is defined as a state property, so that it can be manipulated to affect both the parent and the button.
Next, define the add() and remove() functions to look like:
add() {
this.setState({data: this.state.data + 1});
}
remove() {
this.setState({data: this.state.data - 1});
}
And of course, the constructor bind to this scope (still on the parent)
constructor(props, context) {
this.add = this.add.bind(this)
this.remove = this.remove.bind(this)
}
With these done, you can then define your button as:
<button
type="button"
value={posts.index}
onClick={this.props.data ? this.props.remove : this.props.add}
key={cont._id}
data={this.props.data} >
React strongest belief is that changes in the DOM be triggered by data. With this setup, anytime you make any change to the parent data attribute by calling the add() or remove() callback, the button is re-rendered to reflect the new value of data.