Is it fine to mutate attributes of React-controlled DOM elements directly? - dom

I'd like to use headroom.js with React. Headroom.js docs say:
At it's most basic headroom.js simply adds and removes CSS classes from an element in response to a scroll event.
Would it be fine to use it directly with elements controlled by React? I know that React fails badly when the DOM structure is mutated, but modifying just attributes should be fine. Is this really so? Could you show me some place in official documentation saying that it's recommended or not?
Side note: I know about react-headroom, but I'd like to use the original headroom.js instead.
EDIT: I just tried it, and it seems to work. I still don't know if it will be a good idea on the long run.

If React tries to reconcile any of the attributes you change, things will break. Here's an example:
class Application extends React.Component {
constructor() {
super();
this.state = {
classes: ["blue", "bold"]
}
}
componentDidMount() {
setTimeout(() => {
console.log("modifying state");
this.setState({
classes: this.state.classes.concat(["big"])
});
}, 2000)
}
render() {
return (
<div id="test" className={this.state.classes.join(" ")}>Hello!</div>
)
}
}
ReactDOM.render(<Application />, document.getElementById("app"), () => {
setTimeout(() => {
console.log("Adding a class manually");
const el = document.getElementById("test");
if (el.classList)
el.classList.add("grayBg");
else
el.className += ' grayBg';
}, 1000)
});
And here's the demo: https://jsbin.com/fadubo/edit?js,output
We start off with a component that has the classes blue and bold based on its state. After a second, we add the grayBg class without using React. After another second, the component sets its state so that the component has the classes blue, bold, and big, and the grayBg class is lost.
Since the DOM reconciliation strategy is a black box, it's difficult to say, "Okay, my use case will work as long as React doesn't define any classes." For example, React might decide it's better to use innerHTML to apply a large list of changes rather than setting attributes individually.
In general, if you need to do manual DOM manipulation of a React component, the best strategy is to wrap the manual operation or plugin in its own component that it can 100% control. See this post on Wrapping DOM Libs for one such example.

Related

How to get data from an API only once (on app creation, outside component or view) in Vue3 SPA, with Pinia store

Is it possible and is it a good practice to avoid fetching data from an API every time the router view is loaded or the component is Mounted?
The thing is that some data rarely changes (like a dropdown options list, imagine allowed animal picks for my app) and it's logical not to send a request every time to a server, instead on app creation would be sufficient.
Tried in App.vue, is that a common thing?
IN APP.vue
import { computed, onMounted, onUpdated, ref } from 'vue';
onMounted(()=>{
axios.get('/data')....
.then((res)=>{
store.property = res.data
...
})
})
I think having it on mount in the App.vue component is acceptable since the App component would not be remounted.
The ideal setup, however, depends on some other parameters like size of application and size of team that's maintaining it. In a large applications you might want to organize things in amore structured and consistent way so you and other folks working on the code know where to find things.
You could consider moving the API call into the pinia action.
store.loadMyData()
// instead of
axios.get('/data')
.then((res)=>{
store.property = res.data;
})
That way you have fewer lines of code in the component. Having "lean" components and moving "business logic" out of components usually makes for better organization which makes it easier to maintain.
Within the action, you can track the state of the API
const STATES = {
INIT: 0,
DONE: 1,
WIP: 2,
ERROR: 3
}
export const useMyApiStore = defineStore('myapi', {
state: () => ({
faves: [],
favesState: STATES.INIT
}),
actions: {
loadMyData() {
this.store.favesState = STATES.WIP;
axios.get('/data')
.then((res) => {
this.store.property = res.data;
this.store.favesState = STATES.DONE;
})
.catch((e) => {
this.store.favesState = STATES.ERROR;
})
},
},
getters: {
isLoaded(){
return this.store.favesState === STATES.DONE;
}
isLoading(){
return this.store.favesState === STATES.WIP;
}
}
})
This is, obviously, more verbose, but allows for the components to be smaller and contain less logic. Then, for example, in your component you can use the getter isLoading to display a loading indicator, or use isLoaded inside another component to determine whether to show it.
Yes, this is a oft used way to load some data into the Vue App.
You could also load data before the Mounting in beforeMount() or created() Lifecycle Hooks (see Vue Lifecycle Diagram) to prevent unnecessary HTML updates.

vuejs: How to change the class of each item in v-for

My component template have an img
<img src="img/loading.gif" :data-src="url" class="live-snapshot-img" :class="{lazy:true, 'lazy-loaded': false}">
When it rendered, I'll trigger out the lazy event. The class will changed to 'lazy-loaded' from 'lazy'.
<img src="img/loading.gif" :data-src="url" class="live-snapshot-img lazy-loaded">
Then if the data changed, I want the class change back to 'lazy'. The bind:class doesn't work.
My solution is
Create a method in component
lazyload: function() {
var clazz = {lazy: true, 'lazy-loaded': false}
clazz['dummy' + Math.random()] = true
return clazz
},
and change the img to
<img src="img/loading.gif" :data-src="url" class="live-snapshot-img" :class="lazyload()">
I think you're approaching this in slightly the wrong way. You have the right idea, but I feel like your thinking and jQuery post render dom manipulation manner, not that this is bad, just not right for this situation. Vue works a little differently. If you want to change the class after the event in this particular instance, you bind your :class to a variable in your vue component.
If I wanted to make this happen, I would probably start by setting a variables in my component data for the state. (see: Class and Style Bindings)
Vue.component('my-component-name', {
data: function () {
return {
imageState: {'lazy': true, 'lazy-loaded': false}
}
}
})
Then bind that to your element:
<img src="img/loading.gif" :data-src="url" class="live-snapshot-img" :class="imageState">
You can then manipulate the imageState in your component methods in any way you want.

How to add meta data to a specific word and turn it into a custom type while using decorators with a regex strategy?

I’m struggling at modeling a certain use case of mine with Draft.js.
I’m highlighting certain words/phrases in the editor with a composite decorator by using a regex strategy.
What I’m trying to archive is: if a user clicks on a decorated word, I want to toggle it’s state and store it somehow.
How would I do this? Any clues?
At a higher level, it’s basically a way to ignore certain decorated words, even if they match the regex strategy
I thought that maybe entities could help me do the job here, they would allow me to store such meta information (ex: ignore) on the decorated word, right?
When I faced the similar issue I used the store of the rendered component for storing a condition.
You used a functional component here:
renderAnnotation(type){
return (props)=> {
return (<span className={type} onClick={this.ignoreDecoratedWord.bind(this, props)}>{props.children}</span>);
};
}
You can change it and use standard react component:
renderAnnotation(type){
return (props)=> {
return (<HighlightedWord type={type} {...props} />);
};
}
The HighlightedWord component is:
class HighlightedWord extends React.Component {
constructor() {
super();
this.state = { enable: true }
}
toggleStatus = () => {
this.setState({ enable: !this.state.enable });
}
render() {
return (
<span className={this.state.enable ? this.props.type : ''} onClick={this.toggleStatus}>{this.props.children}</span>
)
}
}
We toggle the highlighting status after the click event.
Check this demo.

Angular 2 + ngrx(redux) + forms

How do you handle Angular 2 forms in unidirectional data flow? Especially with validation between several parent/child components?
I am using ngrx/store and model driven forms with form builder.. Is it possible to do something similar like form reducer in React and make it as a part of Store?
Do you have some articles about it?
I have created a library called ngrx-forms that does exactly what you want. You can get it on npm via:
npm install ngrx-forms --save
I recommend checking out the full README on the github page, but below you can find some examples of what you need to do to get the library up and running once installed.
Import the module:
import { StoreModule } from '#ngrx/store';
import { NgrxFormsModule } from 'ngrx-forms';
import { reducers } from './reducer';
#NgModule({
declarations: [
AppComponent,
],
imports: [
NgrxFormsModule,
StoreModule.forRoot(reducers),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Add a group state somewhere in your state tree via createFormGroupState and call the formGroupReducer inside your reducer:
import { Action } from '#ngrx/store';
import { FormGroupState, createFormGroupState, formGroupReducer } from 'ngrx-forms';
export interface MyFormValue {
someTextInput: string;
someCheckbox: boolean;
nested: {
someNumber: number;
};
}
const FORM_ID = 'some globally unique string';
const initialFormState = createFormGroupState<MyFormValue>(FORM_ID, {
someTextInput: '',
someCheckbox: false,
nested: {
someNumber: 0,
},
});
export interface AppState {
someOtherField: string;
myForm: FormGroupState<MyFormValue>;
}
const initialState: AppState = {
someOtherField: '',
myForm: initialFormState,
};
export function appReducer(state = initialState, action: Action): AppState {
const myForm = formGroupReducer(state.myForm, action);
if (myForm !== state.myForm) {
state = { ...state, myForm };
}
switch (action.type) {
case 'some action type':
// modify state
return state;
default: {
return state;
}
}
}
Expose the form state inside your component:
import { Component } from '#angular/core';
import { Store } from '#ngrx/store';
import { FormGroupState } from 'ngrx-forms';
import { Observable } from 'rxjs/Observable';
import { MyFormValue } from './reducer';
#Component({
selector: 'my-component',
templateUrl: './my-component.html',
})
export class MyComponent {
formState$: Observable<FormGroupState<MyFormValue>>;
constructor(private store: Store<AppState>) {
this.formState$ = store.select(s => s.myForm);
}
}
Set the control states in your template:
<form novalidate [ngrxFormState]="(formState$ | async)">
<input type="text"
[ngrxFormControlState]="(formState$ | async).controls.someTextInput">
<input type="checkbox"
[ngrxFormControlState]="(formState$ | async).controls.someCheckbox">
<input type="number"
[ngrxFormControlState]="(formState$ | async).controls.nested.controls.someNumber">
</form>
This is a fairly old question, but I couldn't find a great solution in my own quest for working with ngrx + reactive forms in Angular. As a result, I'll post my research here with hope that it may help someone else. My solution can be broken down into two parts, and I pray you (oh weathered soul) find it applicable to your problem:
1) Monitor the form element/s (for example, "keyup" event for a typical text input), and update the State from that event. This strategy comes straight out of the book search component in the ngrx example app. We can now successfully populate the State as our form changes. Awesome! 50% done!
2) The angular reactive forms guide demonstrates creating the form group in the constructor. I have seen some other people do it inside ngOnInit, but this is too late in the lifecycle for our needs (I tried, I failed). Now that we have our form group established, setup ngOnChanges to capture any changes pushed from the state, and then update the form group using patchValue. For example:
ngOnChanges(changes: SimpleChanges) {
if (changes.valueICareAbout1) {
this.myForm.patchValue({
valueICareAbout1: changes.valueICareAbout1.currentValue
});
}
if (changes.valueICareAbout2) {
this.myForm.patchValue({
valueICareAbout2: changes.valueICareAbout2.currentValue
});
}
}
In the applications I built with Angular 2, the following guideline seemed to work well:
Parent components pass data down to children via data binding. Child components request data changes by emitting output events to parent components. It is the parent components responsibility to act accordingly.
In a hierarchical component structure, data changes are handled by the lowest component that depends on the data. If there's another component higher up or a sibling that depends on the same data item, pass changes up by emitting events and leave the handling to a higher component.
This scheme works well because, for any data that is relevant to more than one component, there is a single component responsible for performing changes. Changes bubble down automatically. Components are reusable, and changes in the component tree can be easily adapted.
With regard to validation, any component in the ladder between the lowest component emitting a data change request up to the highest component that finally handles the change, any component can effectively cancel the change by not passing it higher up. In most applications, I'd opt for validating data changes at the origin of the change though.
Naturally, child components can still have internal state and need not communicate changes - unless changes are relevant to the parent component.
Form data is inherently a very local state, especially for Angular since ngModel binds to local component variables. The top devs that I know recommend keeping the data for the form localized to that component (ie just use ngModel with local variables). This is because un-submitted form data is almost never shared by various components across your whole application. When the user submits the form then you can dispatch an action with a payload containing the form data to a parent component, to the store, or even to an ngrx/effect to be posted to a server.

ClipboardJS with React, using document.getElementById()

Originally, I had it working fine.
Then I did this and now I can't get it to work
ClipboardField.js
import React from 'react';
export default (props) => {
return(
<div id="clip" data-clipboard-text={props.code} onClick={props.onClick}>
<p> Copy to clipboard.</p>
</div>
);
}
Field.js
class DashWizardTwoCore extends Component {
componentDidMount(){
const btns = document.getElementById('clip');
const clipboard = new Clipboard(btns);
}
componentDidUpdate() {
clipboard.on('success', function(e) {
console.log(e);
});
clipboard.on('error', function(e) {
console.log(e);
});
}
render(){
const someCode = "const foo = 1"
return (
<div>
<ClipboardField code={this.someCode} /> }
</div>
);
}
}
If you take the code out of ClipboardField and into Field it works. It's mostly, how do I use document.getElementById() in my parent component to find something in my child?
Their examples:
https://github.com/zenorocha/clipboard.js/blob/master/demo/constructor-selector.html#L18
https://github.com/zenorocha/clipboard.js/blob/master/demo/constructor-node.html#L16-L17
https://github.com/zenorocha/clipboard.js/blob/master/demo/constructor-nodelist.html#L18-L19
Your code is fine you just have a few issues:
you are binding clipboard.on in componentDidUpdate which won't trigger here since you are not really changing anything (in the ClipboardField component) that triggers this event.
You are passing {this.someCode} in the code prop which would be undefined should just be {someCode}
So it's just a matter of moving your clipboard.on to the componentDidMount right after the new Clipboard and use code={someCode}
https://jsfiddle.net/yy8cybLq/
--
In React whenever you want to access the actual dom element of your component we use what react calls as refs, I would suggest you do this rather than using getElementById as this is the "best practice".
However stateless components (like your ClipboardField component above) can't have refs so you just need to change it to be a normal component.
Here's a fiddle with your code but using refs instead: https://jsfiddle.net/e5wqk2a2/
I tried including links to the react docs for stateless components and refs but apparently don't have enough "rep" to post more than 2 links, anyways quick google search should point you in the right direction.
I adjusted your code and created a simple integration of clipboard.js with React.
Here's the fiddle: https://jsfiddle.net/mrlew/ehrbvkc1/13/ . Check it out.