Unable to understand handling events in react.js [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am practicing react since past two days and when i started 'Handling events' section, i was unable to understand the following piece of code. Can anybody help me with this ?
This is the image of the code that i am trying to understand

That's the binding of react method to the event callback, so we can access the this of the react component class inside the event callback method.
There are three ways to bind your method in react.
In constructor.
One of the best way to bind your functions because constructor will be called only once in the whole react component life cycle.
class Test {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
// Do whatever you want to here
}
}
Use arrow functions. Simple but not recommended because it'll bind and initialize the method for every call of render function, which will reduce the performance.
<button onClick={(e) => this.handleClick(e)}/>
Define arrow function as class property.
class Test {
handleClick = (e) => {
// Do whatever you want to here
}
render() {
return(
...
<button onClick={this.handleClick}/>
)
}
}
For better performance you can use any method from 1 and 3 but try to avoid method 2.

By default there are a number of HTML DOM events and for those events there is a Synthetic event in React which wraps the native event. Refer the official documentation to get an in-depth understanding of those two types of events.
In the above code when the user click on the button, the event which corresponds to click action (i.e. On Click event) will be fired and React will wrap the native event with a syntactic event and invoke the respective event handler function. In the above code, that function is handleClick(). Within that function you can execute your logic which corresponds to the user click action on the button.
Note that by default, the syntactic event will be passed as the first argument to the handleClick() function. Hence, you can write it as below.
handleClick(event) {
console.log(event)
// your logic
}
There is a lot of supported events in React which you can use to capture user actions and modify the behavior of your application accordingly.

Related

How pure should a function be when writing in React? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 17 days ago.
Improve this question
In functional programming, a pure function returns the same value for the same arguments.
I'd like to hear tips for writing in React sometime. I definitely do a lot of thinking at some point.
For example, the onClickHandler in the code below is not a pure function because it depends on an external state change.
const { useState } = require("react")
const Example = () => {
const [list, setList] = useState(["a", "b", "c", "d", "e"])
// Delete item from list, when button is clicked
// This function is non-puer because it uses external state (list, setList)
const onClickHandler = (e) => {
const newList = list.filter(item => item !== e.target.innerText)
setList(newList)
}
return (
<div>
{list.map((item, index) => {
return (
<div key={index}>
<button onClick={onClickHandler}>{item}</button>
</div>
)
}
)}
</div>
)
}
export default Example
In this case, is it good to write these codes as pure functions?
If not, should it be written as a pure function only at the component level?
I want to hear from programmers who are interested in React.
What side-effects are there when you have a component with a click handler?
You have the action of appending/updating HTML elements to the DOM
you have the action of firing an event when the user interacts with it
and you have the action of mutating state.
Which one of these side-effects do you actually manage yourself when you use something like Redux for example? None of them.
A component which does not close over mutable free variables and merely describes the creation of DOM nodes without controlling what should be done with them or with their events when they fire, is pure.
The way you use something like Redux in a functional way is that your click handler should only send a signal to Redux saying "I have been pressed, and here are some contextual infos like the cursor coordinates, etc.". It is another piece of code somewhere else which decides how this event will affect the state, and when you write that external piece of code you don't decide how and when it will be executed either, and you won't even mutate the state yourself.
It is React which appends and updates nodes in the DOM, it is the browser which fires events, it is Redux which updates the state. From the point of view of your pure functional component, there are only inputs parameters and an output which is a description of an action, but is not an action itself. It is a pure function.
When you write functional code you very often voluntarily loose control over the execution by letting a framework manage all the side-effects in a predictable way, so that your code remains pure and declarative.
The paradigm shift is that, instead of having every component handle its state independently and collaborate with other components, like cells in an organism, there is a coordinator which knows about the whole state of the world, receives orderly signals about what happens in the app and takes all the decision regarding the creation of a new, updated but snapshot isolated, state of the world. This new state is then passed to the render function and the cycle starts again, with state flowing in a single direction.
The updated React docs describe "purity" as "always return the same JSX given the same inputs." (I would also add that components' render functions shouldn't have externally visible side effects.)
This isn't quite the same as a purely mathematical or functional programming definition of purity: In your example, each time you call Example, the onClick handler that's passed to the DOM will be a different function instance, and the useState hook gives the possibility of state and mutation. However, it meets React's expectations:
A major purpose of hooks is to allow for side effects and state, so that's okay.
Even if the specific onClick function changes, the behavior ("this node responds to a click event and does XYZ") is the same.
If you did violate React's expectations (by having side effects or by rendering different JSX), then bugs are unlikely.
Beyond that, taking a functional programming style approach and using pure functions can make code more maintainable and can fit better with React's conventions and ecosystem. For example, in your Example:
setList is guaranteed not to change, so it's reasonable to not consider it as an external state dependency for onClickHandler.
onClickHandler can use an updater instead of directly depending on the list state. As explained in the React docs, this isn't required, but it can be helpful (especially once you get into effects, callbacks, and more complex state updates.)
const onClickHandler = (e) => {
setList(list => list.filter(item => item !== e.target.innerText))
}

What is the proper way to create an event handler inside a React function component? [duplicate]

This question already has answers here:
Function inside functional component in React hooks - Performance
(8 answers)
Closed 6 months ago.
I'm currently learning react.js and I just want to ask a question on how to properly create an event handler function inside a function component.
Pardon me since most examples in the official documentation are using class for this types of components.
I have an example code below that seems to work fine, but I'm not sure if this is the correct way/best practice when creating an event handler inside a function component, since every time the state changes I assume that the handleClick function is also recreated isn't it? This affects the performance every time we re-render right?
Say for example when I add more elements inside the return statement that can also trigger an event, and each event has a corresponding event handler that is also declared in that same function component, that might be an overhead for those extreme cases 'isn't that correct?
As far as I know this is not a problem on class components because they have a separate render() method so the event handler functions are not recreated, how do we do this in function components?
function Toggle (props) {
const [isToggleOn, setToggle] = React.useState(false)
function handleClick (e) {
setToggle(() => !isToggleOn)
}
return (
<button onClick={handleClick}>
{isToggleOn ? 'ON' : 'OFF'}
</button>
)
}
If you don't want the handleClick function to be recreated on each render, you should use useCallback hook.
const handleClick = useCallback(() => {
setToggle((previousState) => !previousState)
}, [])
This way, handleClick is created only at the initial render because the useCallback's dependency array is empty.
You might also notice that I removed the usage of isToggleOn and instead use the previous state in the setToggle so your function don't need to depend on isToggleOn.

how to we can remove a component React from the DOM using componentWillUnmount() method? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
when can i use the following method in my React code ?
componentWillUnmount()
please show a examle.
"When can I use the following method in my React code? componentWillUnmount()":
We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.
We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.
The componentDidMount() method runs after the component output has been rendered to the DOM. This is a good place to set up a timer:
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
We will tear down the timer in the componentWillUnmount() lifecycle method:
componentWillUnmount() {
clearInterval(this.timerID);
}
Essentially the componentWillUnmount() method is used whenever you need to do something before the DOM you are currently seeing will be discarded. In this case the clock will be removed from the DOM, so you want to stop the timer before this happens.
You can read more on lifecycle methods here: https://reactjs.org/docs/state-and-lifecycle.html
If your intention is to remove component or element you should do it by conditional rendering, hence, changing the rendering component state.

Reactjs: Passing parameter in onClick method without performance loss [duplicate]

This question already has answers here:
How to avoid bind or inline arrow functions inside render method
(4 answers)
Closed 4 years ago.
I am new to React and I have been told that when passing methods to the onClick handler you should not:
use inline arrow functions
call .bind(this, parameter)
As they both will create a new function on every single render, which has implications or performance
In my code I have a parent component sending a method (asideSelected()) as a prop to the child component. In the child component, I want to call this method with a parameter that my parent component receives. I have created the following solution:
Parent:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
selected: ""
};
this.asideSelected = this.asideSelected.bind(this);
}
asideSelected(selected) {
this.setState({
selected: selected
});
}
render() {
return (
<Aside
selected={this.asideSelected}
/>
);
}
Child:
export default class Aside extends Component {
constructor(props) {
super(props);
this.selected = this.props.selected.bind(this);
this.showSelected = this.showSelected.bind(this);
}
showSelected(e) {
let selected = e.target.className;
this.selected(selected);
}
<div className="profile" onClick={this.showSelected} src={chat}></div>
}
This solution appears to be working, however, so does using inline arrow functions and binding inside of the onClick, I've never seen "bad" re-render and so I don't know if this is actually any different from the other ways of doing it. If it is unclear what I am attempting to do I am using the events target to pass as a parameter instead of doing it directly inside onClick. I am worried that this is a clunky or sub-par solution.
Any input welcome,
Thank you
The render is triggered by the setState().
Any time you update the state: this.setState(), the component and its children will re-render, you may read the doc here
It is unusual and unnecessary to bind to functions in the constructor of a react class. When you add a new function in the react object, for instance asideSelected(){ ... } in your example above, this function is bound to the prototype of the react object.
By adding this.asideSelected = this.asideSelected.bind(this); in your constructer, you create a new instance of asideSelected directly to the object. By doing this you add 2x the same functions.
Regarding the arrow functions, that is just ES6 syntax that auto scopes you code to this without the need to use .bind(this). This is just syntactical ES6 magic and should in theory not have any performance hit and makes your code look nicer.
Binding should be done in constructor and reason for it given in following link.I am not writing all blog here, because it's little bit lengthy. Let me know, if you don't understand it, then I will try to give more explanation.
Link: https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56

React events handling, best practice [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am using React and I have old-style kind of code for handling some events:
componentDidMount = () => {
document.addEventListener('mousedown', this.handleClick);
}
componentWillUnmount = () => {
document.removeEventListener('mousedown', this.handleClick);
}
Is it the right way of setting up event handlers in React? I mean best practice. How would you refactor the above code in the React - way of doing things? I understand when we set up events on individual elements, but I am confused in this particular case.
Ideally in React, you never edit the DOM yourself. You should only update the virtual DOM and then let React handle changes to the DOM.
It seems like you want to call this.handleClick() when any part of the document is clicked. One way you could handle that in the "React" way is to add an onClick prop to a container within like so...
class App extends Component {
constructor() {
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
<div className="container" onClick={this.handleClick}=>
//...the rest of your app
</div>
)
}
}
And then make sure that the margins/padding is set in such a way to make sure that your div covers the whole page.
In react you should not bind eventListeners directly to the DOM as react provides synthetic events which can be and should be used and let react handle the rest.
For more details on Synthetic Events here are the React docs
So in your component you can have pass the parameter to your component onMouseDown and handler its click handler something like:
class SomeClass extends Component {
constructor(props) {
super(props)
this.mouseDownHandler = this.mouseDownHandler.bind(this)
}
mouseDownHandler() {
// do something
}
render() {
return (
<div
onMouseDown={this.mouseDownHandler}
>
</div>
)
}
}
Hope this helps.
Is it the right way of setting up event handlers in React?
What you are doing is perfectly fine.
How would you refactor the above code in the React - way of doing things?
Ideally, you would use the React provided DOM Events when possible, but since this is a global document click listener then your code is correct.

Categories