I want to conditionally render something a div judging by whether the browser window has a vertical scroll bar. My renderElements method pulls from an API and the results vary. I've tried assigning a ref to my div and comparing it's scrollHeight to it's innerHeight in ComponentDidUpdate. Despite cases where the page does have a scrollbar due to multiple results coming in, my hasOverflow variable always returns false. What would be the most ideal way to get this to work?
class ExampleClass extends Component {
componentDidUpdate() {
const element = this.element;
const hasOverflow = element.scrollHeight > element.innerHeight;
console.log(hasOverflow);
}
render() {
<div ref={ el => { this.element = el } }>
{ this.renderElemnts() }
</div>
}
}
innerHeight is a function of the window so element.innerHeight is always undefined, therefore element.scrollHeight > element.innerHeight is always false.
What is you're looking for element.offsetHeight:
https://stackblitz.com/edit/react-vb4quk
If you want to test if the window have scroll, you can check with
document.body.scrollHeight > window.innerHeight
https://stackblitz.com/edit/react-afjlmr?file=index.js
Related
I'm trying to change the state of a sub Component using the onScroll Event Handler but when I run it the state stays the same even with the condition placed all because of the window.pageYOffset staying at 0 hence always making it false.
Header.Frame = function HeaderFrame({ children })
{
console.log(window.pageYOffset)
const [scrolling,setScrolling]=useState(false);
return <Container onScroll={() => setScrolling(window.pageYOffset ===0 ? false:true)}>
{children}</Container>;
}
I need to find a way to get two callbacks, which are trigged when the div/img is visible on the screen and when it is not longer visible. What Can I use on Angular?
<div (onVisibleOnScreen)="doSomething1()" (onDisappearOnScreen)="doSomething2()">
You can use behavior subject to control both state and visibility of the DIV element.
Then invoke a function depending on his state.
Check this working example:
https://stackblitz.com/edit/angular-ivy-4ws3hq?file=src/app/app.component.ts
You can use a HostListener on the window scroll event. At the view initialization and each time the user scroll, you compute if your div/img is on screen with a ViewChild and the window.
#HostListener("window:scroll", [])
onWindowScroll() {
this.onScroll();
}
#ViewChild("myElement") myElement: ElementRef<HTMLDivElement>;
public onScroll(): void {
const windowYVisibility = {
min: window.pageYOffset,
max: window.pageYOffset + window.innerHeight
};
const myElementYVisibility = {
min: this.myElement.nativeElement.offsetTop,
max:
this.myElement.nativeElement.offsetTop +
this.myElement.nativeElement.offsetHeight
};
const isElementVisible =
(windowYVisibility.max > myElementYVisibility.min &&
windowYVisibility.min < myElementYVisibility.min) ||
(windowYVisibility.min < myElementYVisibility.max &&
windowYVisibility.max > myElementYVisibility.max);
}
Here is a working stackblitz
I have an animated component that slides up/down depending on the prop (true or false). I'm using maxHeight: 0 to hide the component (transition is being done with CSS) and that's the default state that's being passed as prop. For the opened style I use a maxHeight much bigger than needed just to make sure the content will fit properly. After it's opened I'm able to get its height by ref and set the maxHeight accordingly.
export default class AnimatedInput extends React.Component {
constructor (props) {
super(props);
this.state = {
height: 600
}
}
componentDidUpdate(prevProps) {
var height = this.refs.inputNode ? this.refs.inputNode.clientHeight : height;
console.log(height);
if (this.props.open === false && prevProps.open === true) {
this.setState({height: height});
}
}
render () {
var {height} = this.state;
let test = this.props.open ? 'boxVisible' : 'boxHidden';
var styles = {
boxHidden: {
...
maxHeight: 0,
},
boxVisible: {
....
maxHeight: height,
}
}
return (
<div style={styles[test]} ref="inputNode">
{this.props.children}
</div>
)
}
}
There are 2 problems with this approach:
The first time it's opened and closed is not smooth due to maxHeight being larger than it should (maybe render the opened one off-screen and get its height first?)
If it's closed before fully opened the height will be lower than it should (I suppose it's an easy fix - just need to stop updating the height value).
Am I on the right track? How would you fix these? Should I stick to CSS or maybe make the transition entirely in JS. Thanks for your suggestions!
You're looking for ReactCSSTransitionGroup. I used this for the exact same thing you are.
I'm using Redux in my app, inside a Component I want to scroll to an specific div tag when a change in the store happens.
I have the Redux part working so it triggers the componentDidUpdate() method (I routed to this compoennt view already).
The problem as far as I can tell, is that the method scrollIntoView() doesn't work properly cos componentDidUpdate() has a default behavior that scrolls to the top overwriting the scrollIntoView().
To work-around it I wrapped the function calling scrollIntoView() in a setTimeout to ensure that happens afeterwards.
What I would like to do is to call a preventDefault() or any other more elegant solution but I can't find where to get the event triggering the 'scrollTop'
I looked through the Doc here: https://facebook.github.io/react/docs/react-component.html#componentdidupdate
and the params passed in this function are componentDidUpdate(prevProps, prevState) ,since there is no event I don't know how to call preventDefault()
I've followd this Docs: https://facebook.github.io/react/docs/refs-and-the-dom.html
And tried different approaches people suggested here: How can I scroll a div to be visible in ReactJS?
Nothing worked though
Here is my code if anyone has any tip for me, thanks
class PhotoContainer extends React.Component {
componentDidUpdate(){
setTimeout(() => {
this.focusDiv();
}, 500);
}
focusDiv(){
var scrolling = this.theDiv;
scrolling.scrollIntoView();
}
render() {
const totalList = [];
for(let i = 0; i < 300; i += 1) {
totalList.push(
<div key={i}>{`hello ${i}`}</div>
);
}
return (
<div >
{totalList}
<div ref={(el) => this.theDiv = el}>this is the div I'm trying to scroll to</div>
</div>
)
};
}
Ok it's been a while but I got it working in another project without the setTimeOut function so I wanted to answer this question.
Since Redux pass the new updates through props, I used the componentWillRecieveProps() method instead of componentDidUpdate() , this allowes you a better control over the updated properties and works as expected with the scrollIntoView() function.
class PhotoContainer extends React.Component {
componentWillReceiveProps(newProps) {
if (
this.props.navigation.sectionSelected !==
newProps.navigation.sectionSelected &&
newProps.navigation.sectionSelected !== ""
) {
this.focusDiv(newProps.navigation.sectionSelected);
}
}
focusDiv(section){
var scrolling = this[section]; //section would be 'theDiv' in this example
scrolling.scrollIntoView({ block: "start", behavior: "smooth" });//corrected typo
}
render() {
const totalList = [];
for(let i = 0; i < 300; i += 1) {
totalList.push(
<div key={i}>{`hello ${i}`}</div>
);
}
return (
<div >
{totalList}
<div ref={(el) => this.theDiv = el}>
this is the div I am trying to scroll to
</div>
</div>
)
};
}
I also struggled with scrolling to the bottom of a list in react that's responding to a change in a redux store and I happened upon this and a few other stackoverflow articles related to scrolling. In case you also land on this question as well there are a few ways this could be a problem. My scenario was that I wanted a 'loading' spinner screen while the list was rendering. Here are a few wrong ways to do this:
When loading = true, render spinner, otherwise render list.
{loading ?
<Spinner />
:
<List />
}
as stated above this doesn't work because the list you might want to scroll to the bottom of isn't rendered yet.
When loading set the display to block for the spinner and none for the list. When done loading, reverse the display.
<div style={{display: loading ? 'block' : 'none'>
<Spinner />
</div>
<div style={{display: loading ? 'none' : 'block'>
<List />
</div>
This doesn't work either since the list you want to scroll to the bottom of isn't actually being displayed likely when you call the scroll.
The better approach for the above scenario is to use a loading that acts as an overlay to the component. This way both the spinner and list are rendered and displayed, the scroll happens, and when the loading is complete, the spinner can be de-rendered or set to be invisible.
I have a parent React component that contains a child React component.
<div>
<div>Child</div>
</div>
I need to apply styles to the child component to position it within its parent, but its position depends on the size of the parent.
render() {
const styles = {
position: 'absolute',
top: top(), // computed based on child and parent's height
left: left() // computed based on child and parent's width
};
return <div style={styles}>Child</div>;
}
I can't use percentage values here, because the top and left positions are functions of the child and parent's widths and heights.
What is the React way to accomplish this?
The answer to this question is to use a ref as described on Refs to Components.
The underlying problem is that the DOM node (and its parent DOM node) is needed to properly position the element, but it's not available until after the first render. From the article linked above:
Performing DOM measurements almost always requires reaching out to a "native" component and accessing its underlying DOM node using a ref. Refs are one of the only practical ways of doing this reliably.
Here is the solution:
getInitialState() {
return {
styles: {
top: 0,
left: 0
}
};
},
componentDidMount() {
this.setState({
styles: {
// Note: computeTopWith and computeLeftWith are placeholders. You
// need to provide their implementation.
top: computeTopWith(this.refs.child),
left: computeLeftWith(this.refs.child)
}
})
},
render() {
return <div ref="child" style={this.state.styles}>Child</div>;
}
This will properly position the element immediately after the first render. If you also need to reposition the element after a change to props, then make the state change in componentWillReceiveProps(nextProps).
This is how I did it
const parentRef = useRef(null)
const handleMouseOver = e => {
const parent = parentRef.current.getBoundingClientRect()
const rect = e.target.getBoundingClientRect()
const width = rect.width
const position = rect.left - parent.left
console.log(`width: ${width}, position: ${position}`)
}
<div ref={parentRef}>
{[...Array(4)].map((_, i) => <a key={i} onMouseOver={handleMouseOver}>{`Item #${i + 1}`}</a>)}
</div>
The right way to do this is to use CSS. If you apply position:relative to the parent element then the child element can be moved using top and left in relation to that parent. You can even use percentages, like top:50%, which utilizes the height of the parent element.