React, Using Refs to scrollIntoView() doesn't work in componentDidUpdate() - javascript

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.

Related

How to properly set focus to a div element in React using createRef

I have a react app that I am working on, and currently, I have a custom-built dropdown that I want to open/close when a user clicks on the trigger(the arrow button), close it when a user selects an option, or close it when a user clicks outside the displayed component.
Here is my code:
For the sake of simplicity, I only added the code that I want help with.
class NavBar extends Component {
constructor(props) {
super(props);
this.state = {
showCurrencies: false,
};
this.handleShowCurrencies = this.handleShowCurrencies.bind(this);
}
componentDidMount() {
this.currencyRef = createRef();
}
componentDidUpdate(prevProps, prevState) {
if (this.state.showCurrencies) return this.currencyRef.current.focus();
}
handleShowCurrencies = () => {
this.setState({
showCurrencies: !this.state.showCurrencies,
});
};
render() {
<div className="currency-switch" onClick={this.handleShowCurrencies}>
{currencySymbol}
<span>
<button>
<img src={`${process.env.PUBLIC_URL}/images/arrow.png`} />
</button>
</span>
</div>
{this.state.showCurrencies ? (
<div
className="dropdown"
tabIndex={"0"}
ref={this.currencyRef}
onBlur={this.handleShowCurrencies}
>
{currencies?.map((currency) => (
<div
key={currency.symbol}
className={`dropdown-items ${currencySymbol === currency.symbol ? "selected" : "" }`}
onClick={() => changeCurrencySymbol(currency.symbol)}
>
{`${currency.symbol} ${currency.label}`}
</div>
))}
</div>
) : null}
}
Currently, directing focus to a div element is working fine, and clicking outside the element as well. However, clicking back on the trigger or even selecting an option is not closing the div element. It seems like it is rendering twice(take a closer look on the console): https://drive.google.com/file/d/1ObxU__SbD_Upxr6qcy5eYO4LSy6Mzq9C/view?usp=sharing
Why is that happening? How can I solve it?
P.S: I don't often ask on StackOverflow, so am not familiar with the process. Please bear with me. If you need any other info, I will be more than happy to provide it.

ReactJS cannot seem to call function after page load

I need to be able update button class styles after page loads.
Tried doing it in Render() and i have seen people talk about setTimeout and setInterval, but this other way with event is working part of the time
ComponentDidMount makes a axios web api call grabs data and in a map all is in render. I need to check local storage and such, and want to update button color and text, so I tried many things, but then tried window.addeventlistener ... this.handleload
Seems to work only part of the time.... its like it is happening TOO FAST, I don't want to add "hack" like timers, but i'm stuck with no idea how to do this.
I tried calling functions in the render as well. Not sure why this is so hard to do.
handleLoad() {
alert('always runs from outside loop');
// loop ONLY runs after refreshing browser several times
for (var i = 0; i < this.state.data.length; i++) {
//rarely makes it in
alert('made it');
document.getElementById("4534552").classList.remove('btn-warning');
}
}
componentDidMount() {
webApi.get('sai/getofflinemembers?userId=N634806')
.then((event) => {
//........
}
// THIS is what i call
window.addEventListener('load', this.handleLoad);
}
render() {
const contents = this.state.data.map(item => (
<button id={item.Member_ID} type="button" onClick={(e) => this.downloadUser(item.Member_ID,e)}
className="btn btn-warning">Ready for Download</button>
)
}
I just need to call a function and loop over all the DOM and change it as needed. Now that has me thinking about react creating a virtual DOM to which i don't know.
Needing to check local storage if a member is already set, then set the class of a bootstrap button to a specific color and text as well.
Thoughts?
Just an advice: If you want to manipulate the DOM, it's better to use refs instead of using document.getElementById. https://reactjs.org/docs/glossary.html#refs
But your problem can be solved by using state to store the css class:
class SomeComponent extends React.Component {
state = {
buttonCSSClass: 'btn btn-warning',
}
componentDidMount() {
webApi.get('sai/getofflinemembers?userId=N634806')
.then((event) => {})
.then(() => this.setState({buttonCSSClass: 'btn'})) // it will update the css class
}
}
render() {
const { data, buttonCSSClass } = this.state
return data.map(item => (
<button
key={item.Member_ID}
id={item.Member_ID}
type="button"
onClick={e => this.downloadUser(item.Member_ID, e)}
className={buttonCSSClass}
>
Ready for Download
</button>
))
}
}

React updating DOM in an unpredictable manner with setState and class names

I'm attempting to do an animation with React and CSS classes. I have created a live demo, if you visit it and click the Start button you will see the text fade in and up one by one. This is the desired animation that I am after.
However, there seems to be issues of consistency when you hit Start multiple times and I cannot pinpoint why.
The Issue: Below is a recording of the issue, you can see the number 1 is not behaving as expected.
live demo
The process: Clicking Start will cancel any previous requestAnimationFrame' and will reset the state to it's initial form. It then calls the showSegments() function with a clean state that has no classNames attached to it.
This function then maps through the state adding a isActive to each segment in the state. We then render out the dom with a map and apply the new state.
This should create a smooth segmented animation as each class gets dropped one by one. However when i test this in Chrome (Version 56.0.2924.87 (64-bit)) and also on iOS, it is very inconsistent, sometimes it works perfectly, other times the first DOM element won't animate, it will just stay in up and visible it's completed transitioned state with "isActive".
I tried to replicate this issue in safari but it worked perfectly fine, I'm quite new to react so i am not sure if this is the best way to go about things, hopefully someone can offer some insight as to why this is behaving quite erratic!
/* MotionText.js */
import React, { Component } from 'react';
import shortid from 'shortid';
class MotionText extends Component {
constructor(props) {
super(props);
this.showSegments = this.showSegments.bind(this);
this.handleClickStart = this.handleClickStart.bind(this);
this.handleClickStop = this.handleClickStop.bind(this);
this.initialState = () => { return {
curIndex: 0,
textSegments: [
...'123456789123456789123456789123456789'
].map(segment => ({
segment,
id: shortid.generate(),
className: null
}))
}};
this.state = this.initialState();
}
handleClickStop() {
cancelAnimationFrame(this.rafId);
}
handleClickStart(){
cancelAnimationFrame(this.rafId);
this.setState(this.initialState(), () => {
this.rafId = requestAnimationFrame(this.showSegments);
});
}
showSegments() {
this.rafId = requestAnimationFrame(this.showSegments);
const newState = Object.assign({}, this.state);
newState.textSegments[this.state.curIndex].className = 'isActive';
this.setState(
{
...newState,
curIndex: this.state.curIndex + 1
},
() => {
if (this.state.curIndex >= this.state.textSegments.length) {
cancelAnimationFrame(this.rafId);
}
}
);
}
render(){
const innerTree = this.state.textSegments.map((obj, key) => (
<span key={obj.id} className={obj.className}>{obj.segment}</span>
));
return (
<div>
<button onClick={this.handleClickStart}>Start</button>
<button onClick={this.handleClickStop}>Stop</button>
<hr />
<div className="MotionText">{innerTree}..</div>
</div>
)
}
}
export default MotionText;
Thank you for your time, If there any questions please ask
WebpackBin Demo
Changing the method to something like this works
render(){
let d = new Date();
const innerTree = this.state.textSegments.map((obj, key) => (
<span key={d.getMilliseconds() + obj.id} className={obj.className}>{obj.segment}</span>
));
return (
<div>
<button onClick={this.handleClickStart}>Start</button>
<button onClick={this.handleClickStop}>Stop</button>
<hr />
<div className="MotionText">{innerTree}..</div>
</div>
)
}
How this helps is that, the key becomes different than previously assigned key to first span being rendered. Any way by which you can make the key different than previous will help you have this animation. Otherwise React will not render it again and hence you will never see this in animation.

on item click, items re-renders and scroll comes to the top which is undesired

I have made a component where I am rendering grids of items. On clicking one item, the item is being selected. However there are many items present so there is scroll bar. Whenever I click on an Item, the component is re-rendered (as I am putting the selectedItem in my state), which further re-renders all the other items. But when I click an item after scrolling to the bottom (or middle), the component renders to the top, however I want that to remain on the position it was being clicked.
The components are as follows :
Full-Screen (made using react-portal, contains onClick and changes its state)
--TilesView (all tiles wrapper which renders all the tiles and has an ajax call)
--all Tiles (single tile element)
The part code is as follows :
FullScreen:
componentDidMount() {
if (this.props.selectedPost) {
this.setState({
selectedPost: {
[this.props.selectedPost[0]]: true
}
});
}
}
render() {
const that = this;
//Todo: User fullpage header when space is updated
return (
<Portal container={() => document.querySelector('body')}>
<div className={styles.container}>
<FullPageForm onHide={that.props.onCancel} closeIcnLabel={'esc'} bgDark={true}>
<FullPageForm.Body>
<span className={styles.header}>{'Select Post'}</span>
<div className={styles.body}>
<ExistingAssets onCreativeTileClicked={this.handlePostClick}
selectedCreatives={this.state.selectedPost}
showSelectedTick/>
</div>
</FullPageForm.Body>
</FullPageForm>
</div>
</Portal>
);
}
handlePostClick = (adCreativeAsset, id) => {
event.preventDefault();
this.setState({
selectedPost: {
[id]: adCreativeAsset
}
});
}
In my handlePostClick, I tried doing event.preventDefault() but it didn't work. I have no clue why this is happening, thanks in advance.
Try changing your handlePostClick definition to
handlePostClick = (e, adCreativeAsset, id) => {
e.preventDefault();
//blah blah what you want
}
and in your JSX change onCreativeTileClicked={this.handlePostClick} to onCreativeTileClicked={this.handlePostClick.bind(this)}.
The event you were prevent-defaulting (stopping propagation in real terms) isn't the real event coming from the click but a synthetic one that can be summoned to fill in for an event when there isn't one. You need to stop propagation for the real event.
Hope this helps.

React set scroll position before component mount

I have the below react component which is essentially a chat-box
render(){
const messages = this.props.messages;
return(
<div id="project_chat">
<h1>{this.props.project[0].project}</h1>
<div className="chat_room">
<div className="messages" ref="messages">
<Waypoint onEnter={this.activateWayPoint}/>
<ul>
{messages.map((message) => {
return(
<Message key={uuid.v4()} message={message}/>
)
})}
</ul>
</div>
<div className="chat_message_box">
<input type='text' onChange={this.handleChange} value={this.state.message} className="message_box" placeholder="enter message"/>
<button className="submit_message" onClick={this.handleSubmit}>Submit</button>
</div>
</div>
</div>
)
}
the problem i faced is the chat messages box starts at the topmost position of the container (scroll position starts at the top). I wanted the scroll position to be at the bottom like a normal chat room.
so i tried doing this:
componentDidMount(){
this.refs.messages.scrollTop = this.refs.messages.scrollHeight
}
this triggers AFTER the component gets mounted i.e - the message box scroll position initially starts at the top and forces its way to the bottom on render.
this is normally fine but i'm using a library called react-waypoint which would help me paginate chat messages. this gets triggered every time i'm at the top of the container.
the unhappy consequence is that because the message box starts at the top initially on mount, the waypoint always gets triggered on mount as well.
my question is whether i can force the message component to start at the bottom position as opposed to starting the top and going to the bottom at the beginning
I tried doing this
componentWillMount(){
this.refs.messages.scrollTop = this.refs.messages.scrollHeight
}
the problem is i dont have access to refs before the component mounts. is there any other way?
What you want is to avoid firing this.activateWayPoint before you've set scrollTop.
You can do this by setting a state variable waypointReady to false initially. Set it to true in componentDidMount.
Then, you can modify this.activateWayPoint to check this.state.waypointReady, and return immediately if it is false.
// inside component
getInitialState() {
return { waypointReady : false }
}
componentDidMount() {
this.refs.messages.scrollTop = this.refs.messages.scrollHeight;
this.setState({ waypointReady : true});
}
activateWayPoint() {
if (! this.state.waypointReady) return;
// Your code here!
// ...
}
You will probably have to bind this inside your render function:
// ...
<Waypoint onEnter={this.activateWayPoint.bind(this)}/>
// ...
Alternately, instead of performing the check inside this.activateWayPoint, you might perform the check inside render:
// ...
<Waypoint onEnter={
this.state.waypointReady ?
this.activateWayPoint :
null
}/>
// ...
This assumes that your component re-renders every time you setState.

Categories