Using Document Object in reactjs on onClick Good or Bad - javascript

Is it good practice to use document object in reactjs onClick ?
I know about useRef, but if we have a parent component and a child component I want to access the child component element in parent componnet.
Do I really have to create multiple refs then forward them in child components?
<div onClick={ () => { const filtersElements = document.querySelectorAll(".filter"); ..restComputation } }> </div>

generally using refs and v-dom are better practice than manipulate real dom directly.
In most cases, and I really mean most cases, you would not need to manipulate the DOM. So Yeah it's not good practice especially in this case where you can use JSX very easily to conditionally toggle those classes inside of your render method. Doing it this way is basically not using React for it's main purpose which is keeping the DOM up to date with the state of your application. As far as what you need to know before you develop in React, basically if you read a little bit of the documentation you'll realize how easily you can utilize state and JSX to solve these problems a lot easier and in a way more maintainable and readable fashion.
One reason I might add for this is handling the UI state of your application without React and manually manipulating DOM is very error prone and hard to maintain. It will get out of control quite fast and lead to hard to debug issues regarding a poorly maintained state.
So yes... passing multiple forwardRef is better.

Related

What is a good practice to access the parent component's ref inside its child?

I'm coding a small library with a simple structure: one parent component can contain multiple components of the same type as direct children. Here is a sample schematic diagram for the app:
By current design, a ChildComponent must address a variety of properties of their parent MainComponent, and I am looking for a good practice that can help achieve that or an alternative of an app structure that will lead to a good practice.
My considerations:
Using Context API. This won't go well with the goal in mind because of the nature of contexts. As per linked documentation:
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
Passing all required props from MainComponent to ChildComponent. Despite I meet this approach quite often, I don't think it is good because it leads to duplicate code.
The simplest way is with Props, as you already mentioned. If you are passing only one level down it is probably the best option:
https://reactjs.org/docs/components-and-props.html
If you need to pass code to several children and grandchildren, using props will get annoying, that is called "propdrilling". You can avoid it using a Context that will provide to all the components that want to consume it:
https://reactjs.org/docs/context.html
Another alternative for larger applications is Redux. Is has a store and enables your components to interact with the Redux store. The downside is that it requires a lot of boilerplate.
https://react-redux.js.org/

Static Class Variables ES6

Is it a good idea to use static properties in ES6. Some of my colleagues believe that it is a bad idea, but I did not get a good explanation as to why it was so.
I am building a ReactJs application, and I use redux wherever necessary, however, when I want to share some data with all the components in the app, can I use static class properties?
In my case it's we want to share the value of a variable called ThemeName across all components. Note that the components do not listen to changes to this variable. It just takes the value of the variable when it loads.
It actually works without any issues, yet somehow I have this feeling that it could be anti patten, can someone please explain the issue here, if any?
It is not a good idea to use static properties with React for a few reasons:
Class properties aren't tapped into the React's lifecycle, so unless these properties are never, ever going to change, static properties are going to be too inflexible.
React itself if moving away from classes in general, so if you are new to React I would recommend not using classes at all. You can read more about the motivation behind this in the official React docs
React cooperates with other mechanisms for accomplishing what you are trying to accomplish, whether that be Redux, or Context

When should I use React hooks? [duplicate]

With the introduction of hooks in React, the main confusion now is when to use function components with hooks and class components because with the help of hooks one can get state and partial lifecycle hooks even in function components. So, I have the following questions
What is the real advantages of hooks?
When to use function components with hooks vs Class components?
For example, function components with hooks can't help in perf as class components does. They can't skip re-renders as they don't have shouldComponentUpdate implemented. Is there anymore reasons?
The idea behind introducing Hooks and other features like React.memo and React.lazy is to help reduce the code that one has to write and also aggregate similar actions together.
The docs mention few really good reason to make use of Hooks instead of classes
It’s hard to reuse stateful logic between components Generally when you use HOC or renderProps you have to restructure your App with multiple hierarchies when you try to see it in DevTools, Hooks avoid such scenarios and help in clearer code
Complex components become hard to understand Often with classes Mutually unrelated code often ends up together or related code tends to be split apart, it becomes more and more difficult to maintain. An example of such a case is event listeners, where you add listeners in componentDidMount and remove them in componentWillUnmount . Hooks let you combine these two
Classes confuse both people and machines With classes you need to understand binding and the context in which functions are called, which often becomes confusion.
function components with hooks can't help in perf as class
components does. They can't skip re-renders as they don't have
shouldComponentUpdate implemented.
Function component can be memoized in a similar way as React.PureComponent with Classes by making use of React.memo and you can pass in a comparator function as the second argument to React.memo that lets you implement a custom comparator
The idea is to be able write the code that you can write using React class component using function component with the help of Hooks and other utilities. Hooks can cover all use cases for classes while providing more flexibility in extracting, testing, and reusing code.
Since hooks is not yet fully shipped, its advised to not use hooks for critical components and start with relatively small component, and yes you can completely replace classes with function components
However one reason that you should still go for Class components over the function components with hooks until Suspense is out for data fetching. Data fetching with useEffect hooks isn't as intuitive as it is with lifecycle methods.
Also #DanAbramov in one of his tweets mentioned that hooks are designed to work with Suspense and until suspense is out it's better to use Class
Hooks greatly reduce the amount of code you need to write and increase its readability.
It is worth noting though that there are hidden processes going on behind (Just like component did mount etc.) that mean if you don't understand what is going on it can be difficult to troubleshoot. It is best to experiment with them and read through the docs fully before implementing on a live project.
Also there is still limited support/documentation for testing hooks compared to classes.
https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga
Update 28/08/2020
Use the react hooks testing library with custom hooks for testing
https://github.com/testing-library/react-hooks-testing-library
Officially it sounds like hooks will completely replace classes?? maybe one day, but think about it; hooks have been around for 3 years (as of Mar 2021), and there are pros and cons in adopting them (More pros than cons... don't get me wrong)
I have plenty more experience myself with state management/classes and after doing a lot of research and testing, I found out that we need to know both classes and hooks very well. Hooks require a fraction of the code for simple components and seem excellent for optimizing HOCs. Meanwhile classes seem better with routing, container components and asynchronous programming for example.
I'm sure there are plenty more cases where each technology is better, but my point is that programmers need know both hooks and classes very well specially when working on projects with 100,000+ lines of code and millions of users. Read more here: https://stackoverflow.com/a/60134353/11239755

React App without state and props

I would like to know if it's fully consistent with the React principles.I made a React App without state and props.I've put pure javascript only inside componentDidMount e.g.
componentDidMount(){
const first = document.getElementById('first');
const second = document.getElementById('second');
function funk(){
console.log(first.innerHTML);
second.innerHTML = "Arrr";
}
funk();
}
Of course it's just an example, my app is far more complex.
Technically speaking, You can (as you may already know).
Should you do it? A big and glowing NO!.
With this approach of targeting the DOM directly, you are bypassing and missing most of the goodness that react has to offer with the Reconciliation and The Diffing Algorithm.
If you really (really) need to target the DOM, you can use react's ref API.
And you can see in their docs it's should be used sparingly :
Don’t Overuse Refs
Your first inclination may be 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. See the
Lifting State Up guide for examples of this.
Yes and no
Yes, you can use it in some cases for utilizing complex jQuery plugins integrating react as a part of your project and so on...
I know that there are lots of haters of such approach but we should also understand business if it's possible to achieve a goal without spending 40-80hrs for coding it yourself - go for it.
No, you should not do any DOM manipulation in component live cycle methods unless you are very good with react and completely understand how things work internally in this library.
Changing DOM in such way will most likely cause performance issues because your components will not be able to utilize shadow DOM, as a result, your components will perform DOM manipulation after every change and could potentially slow down the application.

What is happening in a React component when you used #extend?

What is happening inside here from what I understand is that you're building out your own render method, which will render the html of the h1. This render method is called by React.DOM to figure out what to give to the virtual dom. The same goes for methods such as componentDidMount right? If you put in any of those lifecycle methods or render, React will call them accordingly to fit inside their code, but if create other functions, those will just be helper functions for you to render stuff with, right?
I guess I'm just trying to understand which part of the Component class is being used by React.DOM and which parts am I building. It seems weird that some methods are used to "configure" the component while others are used as helpers. What code inside the Component class is the React.DOM using? Is it like stuff to figure out the diffs on when to rerender stuff?
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Here's something to consider: ages ago in times long past, React and React-DOM were one in the same. React was targeted solely to webapps. So we could use h1, div, span, img, all of that using React only.
Now let me ask you this question. Let's say they wanted to take React, and make it so it could not only render to the DOM of a webpage, but also render the different components of a native mobile application? What would you do in that situation?
Obviously, all of those aforementioned HTML DOM elements, h1s etc etc, would be utterly useless! Android and iOS interiors do not know what any of those are whatsoever.
So the logical solution is to abstract that away. Instead of having those DOM nodes be an inherent part of React, instead make it so that React can render wherever and whatever!
You see, the React engine works pretty much the same in both React Native (mobile development), and standard web-based React with React-DOM. The lifecycle methods, the principles of design, the reconciliation, the entire engine is the same. Because React isn't about HTML or native applications, it's about a paradigm of data flow from application state into UI state.
So then, what is React-DOM doing with your component? Not a whole lot of anything, really. All of the diffing, data flow, etc etc are all handled by React.
What React-DOM does is it knows how to render the data provided by a React element as a DOM node. It knows how to update them, how to delete, them, all of that. You see, having all those abilities as part of the React core would not be ideal now, because React targets other platforms where those abilities are useless. And they would only bloat the package.
The only method inside the class you 'have' to provide is the render. The other component lifecycle methods, as you mentioned, are called if provided when those lifecycle methods come into play. If you have no need to tap into those other lifecycle methods (component just returns some markup based on props provided to it) and your component doesn't need its own state then I would highly recommend just using stateless functional components. The docs provided by React team are good for explaining this -
https://facebook.github.io/react/docs/components-and-props.html
As far as the 'helper methods' you mentioned, yes you can define as many methods as you need in your class. It is very common to split up some of the more complex rendering logic into smaller easier to read functions for code readability.

Categories