I am using React Virtualized to window my items list which has the following functionality
1) onClicking on any item, the user will be prompted with a details panel where he will be able to update the details of the item. And when he goes back to the list, he will be able to see the details in the item cell in the list. He can add a lot of details to make it bigger or reduce the size by removing the details
2) He can delete the item, or add another item to the list with certain details or without details.
CellMeasurer serves my requirement as dynamic height is supported. But I am having following issues with it
1) initially when my list mounts for the first time, first few items are measured and shown correctly but as soon as I scroll to the end, items get overlapped with each other.(positining isnt correct, I am guessing the defaultHeight is being applied to the unmeasured cells). This works fine as soon as the list is rerendered again.
2) Also, when I am updating the details of an item the list doesnt update with the new height adjustments
I am sure that somewhere my implementation is incorrect but have spent a lot of time hammering my head for it. Please let me know what can be done here to fix this
ItemView = props => {
const {index, isScrolling, key, style} = props,
items = this.getFormattedItems()[index]
return (
<CellMeasurer
cache={this._cache}
columnIndex={0}
isScrolling={isScrolling}
key={key}
rowIndex={index}
parent={parent}>
{({measure, registerChild}) => (
<div key={key} style={style} onLoad={measure}>
<div
onLoad={measure}
ref={registerChild}
{...parentProps}>
<Item
onLoad={measure}
key={annotation.getId()}
{...childProps}
/>
</div>
</div>
)}
</CellMeasurer>
)
}
renderDynamicListOfItems(){
return (<div>
<List
height={500}
ref={listComponent => (_this.listComponent = listComponent)}
style={{
width: '100%'
}}
onRowsRendered={()=>{}}
width={1000}
rowCount={props.items.length}
rowHeight={this._cache.rowHeight}
rowRenderer={memoize(this.ItemView)}
// onScroll={onChildScroll}
className={listClassName}
overscanRowCount={0}
/>
</div>
)
}
Also, I am manually triggering the remeasurement of my item in its componentDidUpdate like follows()
Component Item
...
componentDidUpdate() {
console.log('loading called for ', this.props.annotation.getId())
this.props.onLoad()
}
...
In the main parent I am recomputing the heights of the list every time the list has updated and triggering a forceupdate as follows
Component ParentList
...
componentDidUpdate() {
console.log("calling this parent recomputing")
this.listComponent.recomputeRowHeights()
this.listComponent.forceUpdateGrid()
}
...
I just faced the same issue and it turned out to be some layout updates in my Item component, that changed the height of the item after it has been measured by the CellMeasurer.
Fix was to pass down the measure function and call it on every layout update.
In my case it was
images being loaded
and text being manipulated with Twemoji (which replaces the emojis with images).
I also had problems getting the correct height from the cache after prepending some new list items when scrolling to the top of the list. This could be fixed by providing a keyMapper to the CellMeasurerCache:
const [cache, setCache] = useState<CellMeasurerCache>();
useEffect(() => {
setCache(new CellMeasurerCache({
keyMapper: (rowIndex: number, columnIndex: number) => listItems[rowIndex].id,
defaultHeight: 100,
fixedWidth: true,
}));
}, [listItems]);
Related
i'm working on a project where i'm going to be displaying details and information about a certain book page by page inside a pager view as page components, the book contains 500+ pages so i can't just create 500 page components like that and insert them into the pager..what i thought is i can get a specific page, render its component, alongside the previous, and the next page only..and when the user swipes to the next/previous page i would change the component state, and have it re-render with the new 3 pages, the current one, the previous, and the next one. the logic in my head makes perfect sense, but it just won't work when i try to apply it.
can anyone help me, guide me to certain videos that explain this principal more? i feel like i'm missing something.
the code goes like this:
first i have the PagesContainer, here i will create the PagesDetails component(s) based on the current page, and having these pages in react-native-pager-view (you can suggest me a better option). for testing purpose only, i set the swipe end callback (onPageSelected) to increment the current page number state, which would then cause the component to re-render and create the new page component(s), that happens only when the user swipes to new page of course:
function PagesContainer({ currentPageNumber, setCurrentPageNumber }) {
const [pageComponents, setPageComponents] = useState([]);
useEffect(() => {
let compArr = [];
compArr.push(<PageDetails key="current" pageNumber={currentPageNumber} />);
if (currentPageNumber > 1) {
compArr.unshift(<PageDetails key="previous" pageNumber={currentPageNumber - 1} />)
}
if (currentPageNumber <= 500) {
compArr.push(<PageDetails key="next" pageNumber={currentPageNumber + 1} />)
}
setPageComponents(compArr);
}, [currentPageNumber])
return (<PagerView style={{ flex: 1 }}
initialPage={currentPageNumber == 1 ? 0 : 1}
layoutDirection={"rtl"}
onPageSelected={(PageSelectedEvent)=>{setCurrentPageNumber(currentPageNumber + 1)}}
>
{pageComponents.map(page => {
return page;
})}
</PagerView>)
}
and then here i have my PageDeatails component where i simply display texts and details of the page, i take the data from the bookData object which is imported at the very top of the code file:
function PageDetails({ pageNumber }) {
const [pageContent, setPageContent] = useState(null);
useEffect(() => {
setPageContent(bookData[pageNumber]["pageContent"]);
}, []);
return (
<View>
{pageContent && <View>
{pageContent.map(item => {
return (<Text>item</Text>)
})}
</View>
}
</View>
)
}
The logic makes perfect sense in my head but it just doesn't work when i test it..what am i missing? what am i doing wrong?
use the PagerView reference using useRef also store the page index and pass to initialPage get current page index from onPageSelected callback
like:
initialPage={currentPageIndex}
I'm trying to create a Pokedex web app. I have a Card component that displays an individual Pokemon, and within that I have navigation buttons to go back and forth down the list of Cards, and one to exit from the card. I have a function called createCard in the parent component that creates a card in the parent Component.
createCard = (key) => {
const currentCard = (
<Card className="Card"
key={Pokemon[key].key}
id={Pokemon[key].id}
name={Pokemon[key].name}
types={Pokemon[key].types}
img={Pokemon[key].img}
stats={Pokemon[key].stats}
dexEntry={Pokemon[key].dexEntry}
cry={Pokemon[key].cry}
abilities={Pokemon[key].abilities}
sprite={Pokemon[key].sprite}
hideCard={this.hideCard}
createTabs={this.createTabs}
createCard={this.createCard}
/>
)
this.setState({
currentScreen: currentCard
})
}
My issue is that the 'next' and 'previous' navigation buttons don't work (The exit one works fine). The way I set them up is that onclick, they should call the createCard function based on the Pokemon in my dictionary that's key value is one higher or lower than the current one.
<div className="navButtons">
<button className="navBtn" onClick={() => props.createCard(props.key - 1)}>❮</button>
<button className="navBtn" onClick={() => props.hideCard()}>✖</button>
<button className="navBtn" onClick={() => props.createCard(props.key + 1)}>❯</button>
</div>
When I push one of the navigation buttons though, I get "TypeError: Cannot read property 'id' of undefined" and it points to my createCard function. This is my first question on here, so I apologize if it's too lengthy, doesn't contain enough data, or something of the sort.
I am trying to show tooltip on mouse enter and hide on mouse leave.first i make a simple demo which is working fine.
https://codesandbox.io/s/exciting-shannon-4zuij?file=/src/list.js
above code working fine on hover it show's the tooltip and hide on leave.
see same concept i apply on a application.(this code is not working)
https://codesandbox.io/s/cool-liskov-8rvjw?file=/src/App.js
when I hover a item is show the tooltip.but it is not hiding the tooltip when you leaving the item.something went wrong.
const Student = ({students,clickHandler}) => {
console.log(students,"---ee")
const [selectedStudent,setSelectedStudent] = useState(null)
const onMouseHandler = (student,e)=>{
student.visibility = true
setSelectedStudent(student)
}
const onMouseLeaveHandler = (student)=>{
console.log('======',student)
student.visibility = false
setSelectedStudent(student)
}
return (
<ul className="student-container">
{
students && students.length > 0 ? students.map((student,index)=>{
return (
<li key={index} onClick={()=>{
clickHandler(student)
}}
onMouseLeave={()=>{
onMouseLeaveHandler(student)
}}
onMouseEnter={(e)=>{
onMouseHandler(student,e)
}} style={{position:'relative'}}>
<a><span>{student.name}</span></a>
{student.visibility? <ToolTip showToolTip={student.visibility} selectedStudent={selectedStudent}/>:null}
</li>
)
}):null
}
</ul>
);
};
export default Student;
Step too reproduce
Hover on first item Raj
and then try to hover sameer.both tooltip will display.I want only one tooltip will be display which is hovered.
I want my handlers should be in my functional component . I don't want to move these handler to parent component and pass handler as a props
In your demo it's also not work well, - one hide only when open another.
when you set student.visibility you not set state, so nothing has rerendered.
Then when you call setSelectedStudent you pass there just the same referance as was before, since it's the same object, so the state not changed, and again - nothing got rerendered.
What you have to do is pass the updated student in a new variable. like so:
setSelectedStudent({...student})
Then all should work
Given a react-virtualized List with variable content in each row the DOM height needs to be calculated by a rowHeight function - however since that gets called before the row is rendered I am unsure how to actually get the row height.
The examples given for dynamic List row height basically go off a predefined number in the list item's props which doesn't help.
What I think I want to do is render the row on the page at a default height and then get the overflow height on the DOM and set that as the row height. How can I hook into an afterRowRender function or something like that? I imagine performance would suffer so maybe there is a better way of doing this that I am missing.
Check out the docs on CellMeasurer. You can see it in action here.
Basically you'll be looking for something like this:
import React from 'react';
import { CellMeasurer, CellMeasurerCache, Grid } from 'react-virtualized';
const cache = new CellMeasurerCache({
fixedWidth: true,
minHeight: 50,
});
function rowRenderer ({ index, isScrolling, key, parent, style }) {
const source // This comes from your list data
return (
<CellMeasurer
cache={cache}
columnIndex={0}
key={key}
parent={parent}
rowIndex={index}
>
{({ measure }) => (
// 'style' attribute required to position cell (within parent List)
<div style={style}>
// Your content here
</div>
)}
</CellMeasurer>
);
}
function renderList (props) {
return (
<List
{...props}
deferredMeasurementCache={cache}
rowHeight={cache.rowHeight}
rowRenderer={rowRenderer}
/>
);
}
I'm having an issue when I try to render a list of items as follows:
render()
{
const data = (my data);
const cellRenderer = ({index, key}) => (
<li key={key}>
<Datum data={data[index]} />
</li>
);
return (
<AutoSizer>
{
({ width, height }) => (
<CellMeasurer cellRenderer={ cellRenderer }
columnCount={ 1 }
width={ width }
rowCount={ transactions.length }>
{
({ getRowHeight }) => (
<List height={ height }
overscanRowCount={ 50 }
noRowsRenderer={ () => (<div> Nix! </div>) }
rowCount={ transactions.length }
rowHeight={ getRowHeight }
rowRenderer={ cellRenderer }
width={ width } />
)
}
</CellMeasurer>
)
}
</AutoSizer>
);
}
Now when I scroll down it skips every second list-item, until I end up with half the page empty but still scrollable.
When scrolling up it's even worse, it skips half the page.
AutoSizerand CellMeasurer seem to be working fine. I stepped through the code a bit, and it looks like they do create the correct measurement.
My data is just a static array of objects. Not a promise or stream.
I also changed my Datum component a few times to make sure it's completely static markup but that didn't change anything.
Any ideas anybody?
[edit]
Here's a Plunker showing my problem: https://plnkr.co/edit/2YJnAt?p=preview
Ironically, while fiddling with it, I accidentally figured out what I had done wrong. I'll submit an answer with my solution.
Right, I found the problem (and so did #MBrevda! +1!)
The rowRenderer method takes a style that needs to be applied to the rendered list element: https://plnkr.co/edit/FzPwLv?p=preview