Struggle to make virtualized list scrolled to a particular row after content refresh. Scenario: there are few rows, user scrolls to somewhere in the list, and then triggers an event (e.g. presses a button in the app) that modifies the content of the list items. Ideally the user must see the same row at the top of the scroll view that was before the event occurred.
Here is the snippet from my code where I try to make it work with no success.
class MyList extends React.Component {
state = {
newScrollToIndex: undefined
}
// function triggered from outsided events
onCellContentChanged() {
const index = this.listRowIndex
// Don't know really which one to call exactlty
// Just called everything
this.cellMeasurerCache.clearAll()
this.listView.recomputeRowHeights()
this.listView.measureAllRows()
/*
* Tried this did not work at all.
* const off = this.listView.getOffsetForRow({ index })
* this.listView.scrollToPosition(off)
*/
// This two seem to work equivalently with 50% chance to work correctly.
// this.listView.scrollToRow(index)
this.setState({ newScrollToIndex: index })
}
renderInfiniteList({ height, width }) {
return (
<InfiniteLoader
isRowLoaded={this.isRowLoaded}
loadMoreRows={this.loadMoreRows}
rowCount={this.rowCount}
>
{({ onRowsRendered, registerChild }) => {
return (
<List
style={{ outline: 'none' }}
noRowsRenderer={() => (
<NoRows
loading={
this.state.loadingMoreRows || this.state.loadingFields
}
/>
)}
height={height}
width={width}
overscanRowCount={2}
rowCount={this.listViewRowCount}
rowHeight={this.cellMeasurerCache.rowHeight}
deferredMeasurementCache={this.cellMeasurerCache}
rowRenderer={this.rowRenderer}
scrollToIndex={this.state.newScrollToIndex}
onRowsRendered={(o) => {
onRowsRendered(o)
this.listRowIndex = o.startIndex
}}
ref={(listView) => {
registerChild(listView)
this.listView = listView
}}
/>
)
}}
</InfiniteLoader>
)
}
}
Any clarification on what is the proper way to make of this scenario to work is appreciated.
Related
I want to be able to scroll between table components in my React app. I have created a component for a table called FormattedTable which takes in props and displays all the information that I want.
A lot of the tables refer to other tables with clickable text. If you click on a reference to another table and it is not being displayed, I add the table to the display and the app automatically scrolls down to the bottom of the screen where the table has been added. However, if the table is already being displayed, I want the app to scroll to where it is being displayed already.
The clicking on the reference and adding another table all occurs in the FormattedTable.js file.
In my Home.js I have an array of objects called selected and this array contains all the objects that I want to be displayed in tables. I display the tables by mapping through the selected array creating a FormattedTable component on each iteration.
Home.js
<div className="rightColumn" style={{flex: 4}}>
{selected.length > 0 ? selected.map((obj, index) => {
return (
<div style={{width: '60%'}}>
<FormattedTable data={data} selected={selected} obj={obj} index={index} onSelectedChange={setSelected}/>
</div>
)
})
: null}
</div>
Because the FormattedTables are being created dynamically in the Home.js file, I'm not sure how to scroll from one table to another in FormattedTable.js (since there is only 1 file but multiple instances).
Does anyone know how this would be possible to do in the FormattedTable.js file?
What I've tried so far is added a ref to the div that's being dynamically created in Home.js and also passed in a triggerScroll method to the FormattedTable component so that I can trigger the scroll when a reference is clicked on a table. The issue with this though is that it still scrolls to the last element as the value of the ref is (naturally) the last element of the array when the mapping stops.
<div className="rightColumn" style={{flex: 4}}>
{selected.length > 0 ? selected.map((obj, index) => {
return (
<div ref = {scrollRef} style={{width: '60%'}}>
<FormattedTable data={data} selected={selected} obj={obj} index={index} onSelectedChange={setSelected} triggerScroll={scrollToTable}/>
</div>
)
})
: null}
</div>
Fixed myself:
Added an attribute to each object in the selected array called inFocus. The most recently selected object in the array has a value of true for this attribute.
I then added a ternary to setting the ref of the FormattedTable based on the inFocus attribute so only one object will be set as the ref at a time.
FormattedTable.js
//For selecting results
const select = (name) => {
//Deep clone object so that results doesn't change when selected changes
const obj = cloneDeep(data.find(element => element.name === name));
const refObj = data.find(element => element.name === name);
//If object is in the original JSON array
if(typeof refObj !== 'undefined') {
//If object is not in the selected array, add it to selected array
if(selected.find(element => element.name === name) === undefined) {
//Make the new object in focus and remove the focus for all the other objects
obj.inFocus = true;
copy.map((el) => {
if(el.name !== obj.name) {
el.inFocus = false
}
})
handleSelectedChange([...copy, obj]);
}
//Otherwise, set focus to selected object
else {
//Make the selected object in focus and remove the focus for all the other objects
copy.map((el) => {
if(el.name !== obj.name) {
el.inFocus = false
} else {
el.inFocus = true
}
})
handleSelectedChange([...copy]);
}
}
}
return (
<div ref={obj.inFocus ? messagesEndRef : null} style={{display: 'flex', flexDirection: 'row'}}>
...
)
I have a function which creates 2 divs when changing the number of items correspondingly (say if we choose 5 TVs we will get 5 divs for choosing options). They serve to make a choice - only one of two possible options should be chosen for every TV, so when we click on one of them, it should change its border and background color.
Now I want to create a dynamic stylization for these divs: when we click on them, they should get a new class (tv-option-active) to change their styles.
For that purposes I used 2 arrays (classesLess and classesOver), and every time we click on one of divs we should remove a class if it's already applied to the opposite option and push the class to the target element - thus only one of options will have tv-option-active class.
But when I click on a div I do not get anything - when I open the document in the browser and inspect the elements, the elements do not even receive new class on click - however, when I console log the classes variable that should apply to an element, it is the way it should be - "less tv-option-active" or "over tv-option-active". I applied join method to remove the comma.
I checked the name of imported css file and it is ok so the problem is not there, also I applied some rules just to make sure the problem is not there and it worked when it's not dynamic (I mean no clicks are needed).
So my list of reasons causing that trouble seems to be not working.
I also tried to reorganize the code in order to not call a function in render return - putting mapping directly to render return, but this also didn't work.
Can anyone give me a hint why it is that?
Here is my code.
import React from 'react'
import { NavLink, withRouter } from 'react-router-dom'
import './TVMonting.css'
import PageTitle from '../../PageTitle/PageTitle'
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
},
}
render() {
let classesLess = ['less']
let classesOver = ['over']
const tvHandlers = {
tvs: {
decrease: () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
},
increase: () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
},
},
}
const createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
return divsArray.map((i) => {
return (
<React.Fragment key={i}>
<div
className={classesLess.join(
' '
)}
onClick={() => {
const idx = classesOver.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesLess.splice(
idx,
1
)
}
classesLess.push(
'tv-option-active'
)
}}
>
Under 65
</div>
<div
className={classesOver.join(
' '
)}
onClick={() => {
const idx = classesLess.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesOver.splice(
idx,
1
)
}
classesOver.push(
'tv-option-active'
)
// classesOver.join(' ')
}}
>
Over 65
</div>
</React.Fragment>
)
})
}
return (
<div>
<button onClick={tvHandlers.tvs.decrease}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={tvHandlers.tvs.increase}>
+
</button>
{createDivs()}
</div>
)
}
}
export default withRouter(TVMontingRender)
CSS file is very simple - it just adds a border.
P.S. I know that with this architecture when I click on one of the divs all the divs will get tv-option-active class, but for now I just want to make sure that this architecture works - since I'm relatively new in React 🙂Thanks in advance!
Components won't have their lifecycle triggered if you are mutating a variable. You need a state for that purpose, which stores the handled data.
In your case you need some state to say which div has the active class, under or over. You can also abstract each rendered Tv to another Class component. This way you achieve independent elements that control their own class, rather than changing all others.
For that I created a Tv class, where I simplified some of the logic:
class Tv extends React.Component {
state = {
activeGroup: null
}
// this will update which group is active
changeActiveGroup = (activeGroup) => this.setState({activeGroup})
// activeClass will return 'tv-option-active' if that group is active
activeClass = (group) => (group === this.state.activeGroup ? 'tv-option-active' : '')
render () {
return (
<React.Fragment>
<div
className={`less ${ activeClass('under') }`}
onClick={() => changeActiveGroup('under')}
>
Under 65
</div>
<div
className={`over ${ activeClass('over') }`}
onClick={() => changeActiveGroup('over')}
>
Over 65
</div>
</React.Fragment>
)
}
}
Your TvMontingRender will be cleaner, also it's better to declare your methods at your class body rather than inside of render function:
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
}
}
decreaseTvs = () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
}
increaseTvs = () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
}
createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
// it would be better that key would have an unique generated id (you could use uuid lib for that)
return divsArray.map((i) => <Tv key={i} />)
}
render() {
return (
<div>
<button onClick={this.decreaseTvs}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={this.increaseTvs}>
+
</button>
{this.createDivs()}
</div>
)
}
}
Note: I didn't change the key you are passing to Tv, but when handling an array that you manipulate somehow it's often better to pass an unique id identifier. There are some libs for that like uuid, nanoID.
When handling complex class logic, you may consider using libs like classnames, that would make your life easier.
This is how I am currently doing it - it is very uneloquent, and it doesn't work. I am getting
TypeError: Cannot read property '0' of undefined
at grid.push(<Card key={index+x} name={list[index+x][0]} img={list[index+x][1]}/>);
this is my code
const list = // my list of data
var grid = [];
list.map((element, index) => {
if (index%4 == 0) {
if (index<list.length-2) {
const el = (<div className="row">
//card being a component I built
<Card key={index} name={element[0]} img={element[1]}/>
<Card key={index+1} name={list[index+1][0]} img={list[index+1][1]}/>
<Card key={index+2} name={list[index+2][0]} img={list[index+2][1]}/>
<Card key={index+3} name={list[index+3][0]} img={list[index+3][1]}/>
</div>)
grid.push(el);
} else {
let remainder = (list.length-index);
for (var x=0;x+=1;x<remainder) {
grid.push(<Card key={index+x} name={list[index+x][0]} img={list[index+x][1]}/>);
}
}
}
})\
return (
<div>
{grid}
</div>
)
The current way I am doing it is making grid then iterating through the list and adding jsx to it. The problem is that I need to make a row for bootstrap every 4 columns to make the grid, any better ideas, solutions greatly appreciated!
You are using index+1, index+2, index+3 which will never exist in the array, when you reach last element.
Instead calculate it in some other variable to find elements which exist.
Hey Stack OverFlow community I am working on a React project where I am mapping over a set of table rows. Within every table row I have an additional row with more info about each individuals rows data. My issue is that when I click on the button to render additional information for that table it renders all of the additional informations for all of the rows.
I understand that my logic is implemented in a way where every single additional row will show upon a click. What can I do to fix this?
https://codesandbox.io/s/rj8o4r493n
showDrawyer = () => {
let {showDrawyer} = this.state
this.setState({
showDrawyer: !showDrawyer
})
}
renderTableCellData = () => {
let { tableData } = this.props;
return tableData.map((data, index) => {
return (
<Table.Body>
<Table.Row style={{ height: 75 }}>
<Table.Cell onClick={this.showDrawyer}>{data.name}</Table.Cell>
<Table.Cell>{data.number}</Table.Cell>
<Table.Cell>{data.date}</Table.Cell>
<Table.Cell>{data.uid}</Table.Cell>
</Table.Row>
<Table.Row style={{display: this.state.showDrawyer ? '' : 'none' }}>
<Table.Cell>Hidden Row data</Table.Cell>
</Table.Row>
</Table.Body>
)
})
}
state={
shownDrawerIndex:null
}
showDrawyer = (index) => {
this.setState({
shownDrawerIndex:index
})
}
renderTableCellData = () => {
let { tableData } = this.props;
return tableData.map((data, index) => {
return (
<Table.Body>
<Table.Row style={{ height: 75 }}>
<Table.Cell onClick={()=>this.showDrawyer(index)}>{data.name}</Table.Cell>
<Table.Cell>{data.number}</Table.Cell>
<Table.Cell>{data.date}</Table.Cell>
<Table.Cell>{data.uid}</Table.Cell>
</Table.Row>
<Table.Row style={{display: this.state.shownDrawerIndex == index ? '' : 'none' }}>
<Table.Cell>Hidden Row data</Table.Cell>
</Table.Row>
</Table.Body>
)
})
}
You will have to pass the index of the row on click.This will set the state to that index.
React will re-render the component on set state. While doing this it will check for the drawer index value in state.
According to that state value, it will display and hide the drawer
The solution depends on whether you want (1) additional details to be displayed for multiple rows, or whether (2) once you click on one row, only this row's additional details will be shown, and hidden for the one clicked before.
For (1) Add to the tableData array a showDrawyer field which will be tested in order to know whether to display or not to display the additional info for this element.
OnClick should get as parameter the clicked array element and should toggle this element's showDrawyer value.
For (2) - the state variable that decides which row's additional details are displayed will be an index, rather than a toggle. This index will be checked for the additional details display.
I'm using react-virualized 9 with Autosizer, List, and CellMeasurer components. I need to update the row heights when the list data has changed. It appears that since the changes to support React Fiber in version 9 the only public method for CellMeasurer is now measure(). Most of the examples use the previous resetMeasurementForRow() method. The current CellMeasurer doc doesn't seem to have any info on the new public methods. Not sure if I've overlooked something but any help is appreciated.
const cache = new CellMeasurerCache({
defaultHeight: 60,
fixedWidth: true
});
<AutoSizer>
{({ width, height }) => (
<List
deferredMeasurementCache={cache}
height={height}
ref={element => { this.list = element; }}
rowCount={list.length}
rowHeight={cache.rowHeight}
rowRenderer={this.rowRenderer}
width={width}
/>
)}
</AutoSizer>
rowRenderer({ index, key, parent, style }) {
return (
<CellMeasurer
cache={cache}
columnIndex={0}
key={key}
overscanRowCount={10}
parent={parent}
ref={element => { this.cellMeasurer = element; }}
rowIndex={index}
>
{({ measure }) => {
this.measure = measure.bind(this);
return <MyList index={index} data={list[index]} style={style} />;
}}
</CellMeasurer>
);
}
componentWillReceiveProps(nextProps) {
// Some change in data occurred, I'll probably use Immutable.js here
if (this.props.list.length !== nextProps.list.length) {
this.measure();
this.list.recomputeRowHeights();
}
}
I need to update the row heights when the list data has changed.
The current CellMeasurer doc doesn't seem to have any info on the new public methods.
Admittedly the docs could be improved, with regard to the new CellMeasurer. In this case though, you need to do 2 things in respond to your row data/sizes changing:
If a specific list-item has changed size then you need to clear its cached size so it can be remeasured. You do this by calling clear(index) on CellMeasurerCache. (Pass the index of the row that's changed.)
Next you'll need to let List know that its size information needs to be recalculated. You do this by calling recomputeRowHeights(index). (Pass the index of the row that's changed.)
For an example of something similar to what you're describing, check out the example Twitter-like app I built with react-virtualized. You can see the source here.
if (this.props.list.length !== nextProps.list.length) {
cache.clearAll();
}
This helped me! :)