React events handling, best practice [closed] - javascript

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.

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))
}

how to pass an element from other components to a specific component in React.js [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I have a component which called <Header> and another component <AboutMe>, I wanted to pick an element with an id from <AboutMe> and add an event listener onClick.
the thing is whenever i try to use getElementById it returns the element which I wanted but when I try to add the event listener...throws an error.
Related to your title of this question:
You can achieve the passing of data and objects through to child components through the use of attributes where you use your component.
You really don't need to use the DOM to access the elements on the page, and with React being highly dynamic in nature, the DOM is in a constant state of change which can lead to many issues if you try to bypass React.
So if you have your header component used in your app like this...
<PageHeader userData={ userData } />
Then within your component, which is named PageHeader in this example, define the constants as:
const PageHeader = (props) => {
const userData= props.userData;
Note the object name to use with "props" is the same that you used with the attribute name.
Props will contain all attributes that are defined on the attribute where the component is used.
Just to provide another way to use "props" (the name is not significant) I'll include this code snippet too. Notice that react will auto map each one to it's proper constant... which is pretty cool.
const PageHeader = ( props ) => {
const { uischema, schema, path, visible, renderers, userData } = props;
And one last thing that I should mention, is the use of the props.children, which can be very useful too. This is where DivScrollable is defined, and is using the props.children.
const DivScrollable = (props) => {
return (
<div className={styles.divscrollable} >
{props.children}
</div>
);
};
So the power of props.children is that it passes along the contents of what is contained between the opening and closing tags of a component. In this example it's the MyComponent object that is within the props.children object. But it could also include others too since it's "all of the content" between the component tags.
<DivScrollable>
<MyComponent src={props.src}
theme="monotyped"
spacing="4"
enableClipboard="true"
name={null}
/>
</DivScrollable>
To then address the onClick handling, which you mention within the body of your question, you can use use it like the following, where I am reusing the above examples... see the "onClick" addition within the DivScrollable component.
const DivScrollable = (props) => {
const performSomeFunction= (aValue) => {
... code goes here...;
};
return (
<div className={styles.divscrollable}
onClick={() => {
performSomeFunction(true);
}} >
{props.children}
</div>
);
};
I am not sure why you mentioned Header component, but did you try like this?
function clickEvent() {
...
}
const el = document.getElementById("element_id");
el.addEventListener("click", clickEvent, false);

How to share state between state between React sibling component functions? [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 last year.
Improve this question
How do I use share some state data in one React component function with another? Both are children of yet another component. (I am a React newbie so perhaps somewhat naively I tried: 1) defined an exported const from my ap.jsx with a structure whose properties were the state. Seems like when queried the structure was returning null. 2) cannot use props as that's one way one from parent to child).
I suppose the best answer is: it depends.
However, the most simple solution would be to hold the value in a parent component and pass it down to both child components through props.
If you want to skip few nesting levels, you could reach for React context or state management tools like redux but that is already a heavy tool. Hard to say what exactly is best in your case with context you shared so far.
If you want to share state, you can use Context concept or Redux which is a library for sharing library.
Here is some useful link for you.
https://redux.js.org/
https://reactjs.org/docs/context.html
I agree with akds that the best approach depends on the specific details of your scenario, but that the recommended approach would be to have the parent manage the state, unless the complexity of your scenario dictates otherwise.
Here is a rather trivial example with a component class as the parent to manage the state based on an action taken in the one of the child components, with the two child components being stateless components. The key is that the parent passes down a callback function to the child for whatever event in the child relates to the state change that needs to be handled. In this example, that is just a click on one of the child components, but it could be anything.
Example on CodePen.
Here is the code from the CodePen example:
HTML:
<div id="example"></div>
JS:
import * as React from "https://cdn.skypack.dev/react#17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom#17.0.1";
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {child1Selected:false};
}
handleChild1Click(){
this.setState({child1Selected:!this.state.child1Selected});
}
render(){
return (
<div>
<Child1
child1Selected={this.state.child1Selected}
onClick={() => {this.handleChild1Click();}}
style={{width:"100px", height:"100px", backgroundColor:"blue"}}
/>
<Child2
child1Selected={this.state.child1Selected}
style={{width:"100px", height:"100px", backgroundColor:"lightgrey"}}
/>
</div>
);
}
}
function Child1(props){
return (
<div onClick={props.onClick} style={props.style}>
{props.child1Selected ? "I am Selected" : "I am NOT Selected"}
</div>
);
}
function Child2(props){
return (
<div style={props.style}>
{props.child1Selected ? "My Sibling is Selected" : "My Sibling is NOT Selected"}
</div>
);
}
let loadApp = ReactDOM.render(<Parent/>, document.getElementById('example'));
loadApp;

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.

Unable to understand handling events in react.js [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 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.

Categories