How to set autofocus in React? - javascript

I am trying to set the focus on my React page but it doesn't work because the component updates which I think overrides the componentDidUpdate.
is there another way to do this?
this is the code I normally use to focus
document.querySelector("#input-box").focus();

If you are using react you should ideally be using refs and using them to set focus. Check the accepted answer for Set focus on input after render
If you have a problem of the component losing focus a lot, this can happen if the key value that you set for the component is not unique. React uses the key value that you set to track components across render cycles. If the key is generated incorrectly then you can have a scenario where the component loses focus across render cycles. For e.g., a controlled input box when a user is typing in it.

Related

edit middle of string in react always goes to the end

i have a material-ui input in my reactJS app.
everything is fine. but when i try to edit (add or modify) the text in the middle of the string, the cursor always goes to the end of the string after every letter i put.
i assume it's because of the rerender the component after every input change
so if i won't enter the value attribute it will work. but i do want to write it the react way...
any suggestions?
<input value={this.props.value} onChange={this.props.onChange}/>
I recommend using controlled inputs. That will fix the jumping cursor problem and is the React way.
The jumping is caused by the re-render. I assume that this.props.onChange updates a state of the parent component and passes it to this component? It is better to maintain the state of the input in the same component and call the parents chance function from there.

React components for highlighting text and reloading highlights from files

I am working on creating a text highlighter with these functionalities:
It allows the users to select and highlight/unhighlight the text on
the page with different colors.
Load the highlights from a file (search for the words from the file in the page and highlight them).
I was able to create the highlight and delete highlight function using rangy https://github.com/timdown/rangy (which is not a react component), but whenever any component on the page sets the state using (setState method) those highlights disappear.
Also, previously highlighted items are not easily loaded into the page using this method.
That is why I am redeveloping this functionality again, and I want to know what would be the right approach to tackle this issue?
I have been thinking of developing a custom React component for highlighting and adding it to the page, but for this approach, I want to know how to dynamically add the highlights component when the user selects a text on the page without losing it when the state is updated.
A link to a useful resource on how to add dynamic components would be convenient for me as I have been searching for the correct way to tackle this issue for a while and I think I might not be heading in the right direction.
React will re-render anything where the state has changed. This will cause your highlighting to disappear as the elements are not the same even if they appear the same.
React will also intelligently not re-render if you set a unique key property in many cases. This lets React know to reuse the component.
If the state is correctly changing, and you only want to sometimes prevent a re-render, you should implement a shouldComponentUpdate lifecycle method to control the re-render conditions yourself.

React Portal Functional Component

I have a problem to render an input field with an portal.
When I change a the value of the input, it looses focus.
I think it´s because of rerendering on state change.
https://codesandbox.io/s/zk0w1jv6rp
Does anybody know a solution?
UPDATE
Is there a way that the Bar-Componet will be reused? Lets say I could add something like a key property, so that react knows that it´s the same component and can reuse it.
Its because each time HelloReact component re-render, you are defining a new Bar component and creating a new Bar component, that is not a good approach.
Simple solution is use autoFocus, so each time when it create a new Bar component, it will focus the input element.
Working code.
Better way would be to define Bar component outside of HelloReact component and pass the value and onChange event handler in props. In that case you don't need to use autoFocus.
Example.

Controlled vs uncontrolled components in React

Almost in every ReactJS tutorial or even in the official documentation for handling input changes, onChange is recommended. We use a state for the value and change it via onChange. This triggers the render in every key stroke. So,
Is rendering really that cheap?
Is input value not being held in DOM? So there is no difference between the DOM and VirtualDOM, so although the rendering happens nothing changes? (Wrong assumption probably).
Just for fun and learning purposes I tried those:
Used a custom function and variable to hold the value, set the state after last input not for in every keystroke, passed that value related component etc.
Used onBlur instead of onChange.
But, I don't like either of them and want to ask this question. If live input value changes is not important for us, we only care for the last input, still onChange is the way to go?
React handles the re-rendering very efficiently.It only re-renders the changes.
There are two ways to configure the inputs
First: Controlled Input
With a controlled input, you specify the value of the input with a state variable generally(or even a prop in some cases). In this case you need to call the onChange function to set the state(or the prop) since the value is set to a state/prop and you need to change that to change the value otherwise it will remain the same.
Ex
<input value={this.state.textVal} onChange={(e) => this.setState({textVal: e.target.value}) />
The advantages of having a controlled input is that you have the value available throughout you React component and you do not need an event to be fired on input or access the DOM to get the value.
Second: Uncontrolled input
In this case you don't need an onChange handler to get the input as you don't specify a custom value for the input. The value of the input can be fetched by accessing the dom or from an event object
Ex:
<input type="text" onBlur={(e) => {console.log(e.target.value)}/>
The other way to get the input value will be by accessing the DOM which we do using refs as this.inputVal.value
See this answer on how to use ref:
In React .js: is there any function similar like document.getElementById() in javascript ? how to select certain object?
Regarding you question on React virtualDOM
The virtual DOM is used for efficient re-rendering of the DOM. This isn't really related to dirty checking your data. You could re-render using a virtual DOM with or without dirty checking. There is some overhead in computing the diff between two virtual trees, but the virtual DOM diff is about understanding what needs updating in the DOM and not whether or not your data has changed.
Virtual tree is re-renderd only when the state changes. So using an observable to check if the state has changed is an efficient way to prevent unnecessary re-renders, which would cause lots of unnecessary tree diffs.
For me, the major reason to use controlled components, aside from real time validation, is the principle of "Single Source of Truth."
In the case of an uncontrolled component, the value of the input may be different between the form input and the one used in your React component. You may fetch the new value onBlur, but there are ways that the value in DOM can change without emitting this event, and in that case the value that the user sees and the one that you are working on may differ, resulting in a different result from what the user expects.
This may not be a huge concern, but since React preaches this principle a lot (like not keeping values in state that can be derived from other states), I'd just do it for the sake of consistency.
Besides, you do not need to worry about the cost of re-rendering on each input.

Does Angular 2 have re-rendering optimization?

I have been using React from couple of months and React doesn't simply re-rendering a component completely instead it finds the difference and makes those changes. Does Angular 2 does something like this?
And also whenever a change in state is detected does Angular 2 re-render all the components from the root node or does it only re-render those specific components and their sub-tree whose change is detected?
React doesn't simply re-rendering a component completely instead it finds the difference and makes those changes. Does Angular 2 does something like this?
Conceptually yes, it does not re-render entire components.
Angular builds a change detector object for each component/directive. Template bindings (which includes input property bindings) are tracked inside these change detector objects. When change detection runs, by default, each binding is dirty checked for changes. If a change is found, the changed value is propagated to the child component (if an input property changed) or to the DOM. That's it. The entire template/view is not re-rendered. Only the changed values are updated in the DOM. When Angular change detection finishes, the browser notices the DOM changes and updates what we see on the screen.
whenever a change in state is detected does Angular 2 re-render all the components from the root node or does it only re-render those specific components and their sub-tree whose change is detected?
Angular doesn't detect changes to some model/data objects. Rather, it only detects changes to template bindings.
By default, each time change detection runs, it starts from the root component and checks all components for changes, in depth-first order, using those change detector objects. As described above, only template bindings with changes are updated. So, I wouldn't say that Angular ever re-renders a component... it only modifies those parts of the DOM where a template binding changed.
You can configure a component to use the OnPush change detection strategy to limit when that component and its descendants are checked for changes. You can also completely detach() a component from the change detector tree, which means that component and its descendants will not be change detected until you reattach().
Angular is not using virtual DOM as React do. No need for that in context of Angular.
If you have <input> and need to set its value in runtime to something else you don't need to change all DOM around it. You just call setValue() on that element and that's it.
The same applies to any other DOM element. For example if you have this:
<div>{{someVar}}</div>
and Angular detects that someVar was changed it will change content of only that particular <div>.
Angular only renders where it detects changes.
AFAIK there is some room for improvments in *ngFor where it sometimes re-renders too many items when some are added/removed in the middle or the beginning but that is a known issue and will be fixed eventually.
From my comment below
In fact Angular doesn't need re-rendering optimization because it only does anything when bound values change and then it only changes the DOM where it is bound to the changed value. Angular doesn't have a virtual DOM that it needs to mirror to the actual DOM.
Angular2 is using zone.js for onChange rendering. Usually when a change is detected, it will trigger changeDetection that component and all the children, but you also can have control to change that, to force render some things or not render when you don't like angular2 behavior.
Here is a very good talk about how Angular2 change detection works : https://www.youtube.com/watch?v=CUxD91DWkGM
LE: Just to clarify, it will not re-render the component and all the children, it will detect and trigger changes for all of those, but will render only what is necessary.

Categories

Resources