How do you use useRef with this library? #116
Answered
by
crimx
tansanDOTeth
asked this question in
Q&A
-
This is a common example of useRef with Rxjs. const InputBox = () => {
const buttonEl = React.useRef(null);
useEffect(() => {
const clicky = fromEvent(buttonEl.current, 'click').subscribe(clickety =>
console.log({ clickety })
);
return () => clicky.unsubscribe();
}, []);
return (
<button ref={buttonEl} type="button">
Click Me
</button>
);
}; It seems you can't access the reference in the following because it is const clicky = useObservable(() => fromEvent(buttonEl.current, 'click').subscribe(clickety =>
console.log({ clickety })
)) |
Beta Was this translation helpful? Give feedback.
Answered by
crimx
May 27, 2023
Replies: 1 comment 2 replies
-
If you need a click event stream, there is an example from the docs: import { useObservableCallback, useSubscription } from 'observable-hooks'
const Comp = () => {
const [onChange, textChange$] = useObservableCallback<
string,
React.FormEvent<HTMLInputElement>
>(event$ => event$.pipe(
pluck('currentTarget', 'value')
)) // or just use "pluckCurrentTargetValue" helper
useSubscription(textChange$, console.log)
return <input type="text" onChange={onChange} />
} If you need a dom stream: import React, { useRef } from 'react';
import { switchMap, fromEvent, Observable } from 'rxjs';
import { useObservable, useSubscription } from 'observable-hooks'
export function App() {
const elRef = useRef()
const el$ = useObservable(() => new Observable(sub => sub.next(elRef.current)));
const clicky$ = useObservable(() => el$.pipe(
switchMap(el => fromEvent(el, "click"))
));
useSubscription(clicky$, console.log);
return (
<div className='App' ref={elRef}></div>
);
} Maybe I should add a |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
crimx
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you need a click event stream, there is an example from the docs:
If you need a dom stream: