react-virtualized#List JavaScript Examples
The following examples show how to use
react-virtualized#List.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: app-searchable.js From ThreatMapper with Apache License 2.0 | 6 votes |
VirtualizedList = (props) => {
const rows = props.children;
const rowRenderer = ({ key, index, style }) => (
<div key={key} style={style}>{rows[index]}</div>
);
return (
<List
style={{ width: '100%' }}
width={750}
height={300}
rowHeight={30}
rowCount={rows.length || 0}
rowRenderer={rowRenderer}
/>
);
}
Example #2
Source File: virtual-list.js From Lynx with MIT License | 6 votes |
render() {
const {items} = this.props;
return (
<List
ref={(instance) => {
this.List = instance;
}}
rowHeight={({index}) => items[index].height}
rowRenderer={({index}) => {
const {value} = items[index];
return <SortableItem index={index} value={value} />;
}}
rowCount={items.length}
width={400}
height={600}
/>
);
}
Example #3
Source File: CampaignCannedResponsesForm.jsx From Spoke with MIT License | 5 votes |
SortableList = SortableContainer(List, { withRef: true })
Example #4
Source File: ScriptList.jsx From Spoke with MIT License | 5 votes |
export default function ScriptList({ scripts, onSelectCannedResponse }) {
const [showCopySnackbar, setShowCopySnackbar] = useState(false);
function Row({ index, style, key }) {
const script = scripts[index];
return (
<div key={key} style={style}>
<CannedResponseListItem
key={script.id}
response={script}
labels={script.labels}
onClick={() => onSelectCannedResponse(script)}
/>
</div>
);
}
return (
<div style={inlineStyles.responseContainer}>
{!!scripts.length && (
<AutoSizer>
{({ height, width }) => (
<List
height={height}
rowCount={scripts.length}
rowHeight={250}
width={width}
rowRenderer={Row}
/>
)}
</AutoSizer>
)}
<Snackbar
open={showCopySnackbar}
message="Response copied to the clipboard"
autoHideDuration={2000}
onRequestClose={() => {
setShowCopySnackbar(false);
}}
/>
</div>
);
}
Example #5
Source File: list.js From Nextjs-ja-translation-docs with MIT License | 5 votes |
render() {
const { width } = this.state;
const isTablet = width < 960;
const isMobile = width < 640;
return (
<Container wide gray center>
<div className="container">
<style jsx>{`
.container {
margin: 1rem 0 6rem;
}
.spacer {
margin-top: 2rem;
}
.icon-label {
margin-right: 0.625rem;
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
`}</style>
<WindowScroller serverHeight={800}>
{({ height, isScrolling, onChildScroll, scrollTop }) => (
<List
autoHeight
height={height}
isScrolling={isScrolling}
onScroll={onChildScroll}
scrollTop={scrollTop}
width={width}
rowCount={Math.ceil(dataSource.length / (isMobile ? 1 : isTablet ? 2 : 3))}
estimatedRowSize={500}
rowHeight={args => getRowHeight(args, isMobile ? 1 : isTablet ? 2 : 3) * ROW_HEIGHT}
rowRenderer={isMobile ? MobileRow : isTablet ? TabletRow : Row}
overscanRowCount={5}
overscanIndicesGetter={args => this.overscanIndicesGetter(args, isTablet)}
style={{
willChange: '',
margin: 'auto'
}}
ref={list => {
const columnCount = isMobile ? 1 : isTablet ? 2 : 3;
if (columnCount !== this.lastColumnCount) {
// reset row height for responsive width
this.lastColumnCount = columnCount;
list.recomputeRowHeights();
}
}}
/>
)}
</WindowScroller>
<div className="spacer" />
<Button onClick={() => scrollTo(0)}>
<div className="flex-center">
<span className="icon-label">Back to Top</span>
<ArrowUpIcon color="#0070f3" />
</div>
</Button>
<div className="spacer" />
<Button href={links.submitShowcase} invert>
<span className="icon-label">Share Your Website</span>
<HeartIcon color="white" />
</Button>
</div>
</Container>
);
}
Example #6
Source File: virtual-list.jsx From intergalactic with MIT License | 5 votes |
Demo = () => {
const [data, updateDate] = useState(list);
const innerRef = useRef();
const ref = (node) => {
node = findDOMNode(node);
if (node) {
innerRef.current = node.querySelector('.ReactVirtualized__Grid__innerScrollContainer');
}
};
return (
<Flex direction="column" inline>
<Flex alignItems="center" mb={2}>
<Button
onClick={() => {
updateDate(data.concat(undefined));
}}
>
ADD
</Button>
<Button ml="10px" onClick={() => updateDate(data.slice(0, -1))}>
REMOVE
</Button>
<Text bold ml="10px">
Count: {data.length}
</Text>
</Flex>
<Box h={500}>
{data.length ? (
<ScrollArea inner={innerRef}>
<ScrollArea.Container
ref={ref}
tag={List}
height={500}
rowCount={data.length}
width={500}
rowHeight={120}
rowRenderer={renderRow}
/>
<ScrollArea.Bar orientation="vertical" />
</ScrollArea>
) : null}
</Box>
</Flex>
);
}
Example #7
Source File: ReactVirtualizedList.js From sampo-ui with MIT License | 4 votes |
ReactVirtualizedList = props => {
const classes = useStyles(props)
const { results } = props.perspectiveState
useEffect(() => {
props.fetchResults({
resultClass: props.resultClass,
facetClass: props.facetClass
})
}, [])
useEffect(() => {
const { facetUpdateID } = props
if (facetUpdateID > 0) {
props.fetchResults({
resultClass: props.resultClass,
facetClass: props.facetClass
})
}
}, [props.facetUpdateID])
const rowRenderer = ({
key, // Unique key within array of rows
index, // Index of row within collection
isScrolling, // The List is currently being scrolled
isVisible, // This row is visible within the List (eg it is not an overscanned row)
style // Style object to be applied to row (to position it)
}) => {
const data = props.perspectiveState.results[index]
let image = null
if (data.imageURL) {
const { imageURL } = data
image = imageURL.includes(', ') ? imageURL.split(', ')[0] : imageURL
}
return (
<div className={classes.rowRoot} key={key} style={style}>
<Link className={classes.link} to={data.dataProviderUrl}>
<Card>
<CardActionArea>
{image &&
<CardMedia
component='img'
alt='Kuva löydöstä'
height='140'
image={image}
title='Kuva löydöstä'
/>}
<CardContent>
<Typography gutterBottom variant='h5' component='h2'>
{data.findName}
</Typography>
<Typography variant='body2' color='textSecondary' component='p'>
<strong>{intl.get('perspectives.finds.properties.objectType.label')}: </strong>
{data.objectType}
</Typography>
<Typography variant='body2' color='textSecondary' component='p'>
<strong>{intl.get('perspectives.finds.properties.material.label')}: </strong>
{data.material}
</Typography>
<Typography variant='body2' color='textSecondary' component='p'>
<strong>{intl.get('perspectives.finds.properties.period.label')}: </strong>
{data.period}
</Typography>
<Typography variant='body2' color='textSecondary' component='p'>
<strong>{intl.get('perspectives.finds.properties.municipality.label')}: </strong>
{data.municipality}
</Typography>
</CardContent>
</CardActionArea>
</Card>
</Link>
</div>
)
}
const getRowHeight = ({ index }) => {
const data = props.perspectiveState.results[index]
let height = 300
if (!data.imageURL) {
height -= 140
}
if (data.findName.length > 26) {
height += 32
}
if (data.findName.length > 40) {
height += 54
}
if (data.period) {
const limit = window.innerWidth < 328 ? 25 : 34
if (data.period.length > limit) {
height += 20
}
}
return height
}
const validResults = () => {
const { results, resultClass } = props.perspectiveState
if (resultClass !== props.resultClass) { return false }
if (results == null) { return false }
if (results.length < 1) { return false }
return true
}
// if (props.perspectiveState.results) {
// props.perspectiveState.results.map(r => {
// if (r.period && r.period.length > 33) {
// console.log(r)
// }
// })
// }
return (
<div className={classes.root}>
{(!validResults() || props.perspectiveState.results.fetching)
? (
<div className={classes.progressContainer}>
<CircularProgress />
</div>
)
: (
<AutoSizer>
{({ height, width }) => (
<List
className={classes.list}
height={height}
width={width}
rowCount={results.length}
rowHeight={getRowHeight}
rowRenderer={rowRenderer}
/>
)}
</AutoSizer>
)}
</div>
)
}
Example #8
Source File: index.js From AED-Map with MIT License | 4 votes |
ItemList = ({
isLoading,
defibrillators,
activeDef,
fetchDefItems,
filter,
totalCount,
page,
search,
setMapCenterCoords,
setMapZoomParam
}) => {
const classes = useStyles();
const noData = !isLoading && !defibrillators.length;
const showMessage =
(isLoading && !defibrillators.length) || noData;
const showHorizontalLoader =
isLoading && !!defibrillators.length;
let message;
switch (true) {
case isLoading:
message = 'Завантаження...';
break;
case noData:
message = 'Даних не знайдено...';
break;
default:
message = '';
}
const cache = new CellMeasurerCache({
fixedWidth: true,
defaultHeight: 100
});
const handleScroll = event => {
const { scrollHeight, scrollTop, clientHeight } = event;
if (
totalCount >= page &&
scrollHeight - Math.ceil(scrollTop) <= clientHeight
) {
fetchDefItems({ page, ...filter, ...search });
}
};
// eslint-disable-next-line react/prop-types
const rowRenderer = ({ key, index, style, parent }) => {
return (
<CellMeasurer // dynamically calculates the height of every item
key={key}
cache={cache}
parent={parent}
columnIndex={0}
rowIndex={index}
>
<DefItem
styleParam={style}
defItemInfo={defibrillators[index]}
/>
</CellMeasurer>
);
};
useEffect(() => {
if (!defibrillators.length) {
fetchDefItems();
}
return () => {
defsCancelToken.cancel();
};
// eslint-disable-next-line
}, []);
useEffect(() => {
if (activeDef) {
const [lng, lat] = activeDef.location.coordinates;
setMapCenterCoords({
lng,
lat
});
setMapZoomParam(BASE_ZOOM_VALUE);
}
// eslint-disable-next-line
}, [activeDef]);
return (
<div className={classes.listOuterStyle}>
<AutoSizer>
{({ width, height }) => {
// AutoSizer expands list to width and height of parent automatically
return (
<List
onScroll={handleScroll}
className={classes.listStyle}
width={width}
height={height}
deferredMeasurementCache={cache}
rowCount={defibrillators.length}
rowHeight={cache.rowHeight}
rowRenderer={rowRenderer}
overscanRowCount={10}
/>
);
}}
</AutoSizer>
{showMessage && <InfoMessage>{message}</InfoMessage>}
{showHorizontalLoader && <HorizontalLoader />}
</div>
);
}
Example #9
Source File: SearchInput.js From covid-19 with MIT License | 4 votes |
SearchInput = (props) => {
const classes = useStyles();
const world = useContext(WorldContext);
const [results, setResults] = React.useState([]);
// Force the search index to lazy load
React.useEffect(() => {
world.get(Path.root(), SearchIndexComponent);
});
const onClose = () => {
setResults([]);
};
const onChange = (e) => {
const search = world.get(SEARCH_INDEX_PATH, SearchIndexComponent);
if (!search) {
return;
}
setResults(search.search(e.target.value));
};
const onChoice = (e, path) => {
e.preventDefault();
setResults([]);
props.onChoice(path);
};
const resultRenderer = ({index, key, style}) => {
const {name, path} = results[index];
return (
<div key={key} style={style} className={classes.result}>
<MaterialLink href="#" onClick={(e) => onChoice(e, path)}>
{name}
</MaterialLink>
</div>
);
};
return (
<ClickAwayListener onClickAway={onClose}>
<div className={`${classes.root} ${props.className || ''}`}>
<SearchIcon className={classes.searchIcon} />
<InputBase
className={classes.input}
onChange={onChange}
placerholder="Search..." />
{props.onGeolocate &&
<Divider className={classes.divider} />
}
{props.onGeolocate &&
<IconButton
size="small"
className={classes.iconButton}
onClick={props.onGeolocate}>
<LocationSearchingIcon />
</IconButton>
}
<Paper
className={
`${classes.resultsContainer} `
+ (results.length === 0 ? 'hide' : '')
}
elevation={3}>
<AutoSizer disableHeight>
{({width}) => (
<List
className={classes.resultsList}
rowCount={results.length}
rowHeight={RESULT_HEIGHT}
rowRenderer={resultRenderer}
width={width}
height={Math.min(RESULTS_MAX_HEIGHT, RESULT_HEIGHT * results.length)}
/>
)}
</AutoSizer>
</Paper>
</div>
</ClickAwayListener>
);
}
Example #10
Source File: WebChatListView.js From WhatsApp-Clone with MIT License | 4 votes |
WebChatListView = ({ onItemClick, userChatList }) => {
var [state, dispatch] = useReducer(chatListReducer, initialChatListState);
var { chatList, chatItem, refresh, userId } = state;
useEffect(() => {
listenSocket();
}, []);
useEffect(() => {
if (refresh) {
getLatestChats();
}
}, [refresh]);
useEffect(() => {
// console.log("Chat List Changed == ", JSON.stringify(chatList));
if (chatItem != "") {
renderChats();
}
}, [chatItem]);
function getUserId() {
const userId = getLocalData(webConstants.USER_ID);
dispatch({ type: webConstants.USER_ID, payload: userId });
return userId;
}
const getLatestChats = () => {
getUserId();
getChatList()
.then((res) => {
// console.log("LIST RESPONSE => " + JSON.stringify(res.data.data));
if (res.status === 200) {
userChatList(res.data.data);
dispatch({ type: CHAT_LIST, payload: res.data.data });
}
dispatch({ type: REFRESH, payload: false });
})
.catch((error) => {
console.log("ERROR ", error);
});
};
async function renderChats() {
let chatArray = chatList;
console.log("Message CHAT Received => ", JSON.stringify(chatItem));
var isMatch = false;
if (chatArray.length > 0) {
for (let i = 0; i < chatArray.length; i++) {
const element = chatArray[i];
if (chatItem && element.roomId === chatItem.roomId) {
// Increment unread count
chatItem = await calcUnreadCount(chatItem, element.chatUnreadCount);
// Since chat item received is an object to convert it to array and they re initialise
// if (chatItem.chat.length <= 0) {
chatItem.chat = [chatItem.chat];
// }
console.log("Selected Chat Received => ", JSON.stringify(chatItem));
chatArray[i] = chatItem;
isMatch = true;
break;
}
}
if (!isMatch && chatItem.chatUnreadCount.type != 'reset') {
// Increment unread count
chatItem = await calcUnreadCount(chatItem, 0);
// Since chat item received is an object to convert it to array and they re initialise
// if (chatItem.chat.length <= 0) {
chatItem.chat = [chatItem.chat];
// }
console.log("Selected Chat Received => ", JSON.stringify(chatItem));
chatArray.push(chatItem);
}
console.log("Message CHAT AFTER Received => ", JSON.stringify(chatItem));
dispatch({ type: CHAT_LIST, payload: chatArray });
console.log(
`FINAL CHAT ARRAY ${refresh} => `,
"JSON.stringify(chatArray)"
);
} else {
// For new chat
if (chatItem.chatUnreadCount.type === "add") {
dispatch({ type: REFRESH, payload: true });
}
}
}
function listenSocket() {
// socket.removeListener(webConstants.CHAT_LIST);
socket.on(webConstants.CHAT_LIST, (chatItem) => {
dispatch({ type: CHAT_ITEM, payload: chatItem });
});
}
function calcUnreadCount(chatItem, originalCount) {
// const userId = getLocalData(webConstants.USER_ID);
if (chatItem.chatUnreadCount.userId != userId) {
if (chatItem.chatUnreadCount.type === "reset") {
chatItem.chatUnreadCount = 0;
} else if (chatItem.chatUnreadCount.type === "add") {
chatItem.chatUnreadCount = originalCount ? originalCount + 1 : 1;
} else {
chatItem.chatUnreadCount = 0;
}
} else if (chatItem.chatUnreadCount.type === "reset") {
chatItem.chatUnreadCount = 0;
} else {
chatItem.chatUnreadCount = originalCount;
}
return chatItem;
}
return (
<div
style={{
flex: 1,
width: "100%",
borderRadius: 0,
backgroundColor: WHITE,
}}
>
{chatList.length === 0 && (
<EmptyComponent message={"No chats, contacts or messages found"} />
)}
<List
style={{
height: "100%",
width: "100%",
outline: "none",
}}
rowCount={chatList.length}
height={window.innerHeight}
width={window.innerWidth - window.innerWidth / 3.2}
rowHeight={cache.rowHeight}
rowRenderer={({ index, parent, key, style }) => (
<CellMeasurer
key={key}
cache={cache}
parent={parent}
columnIndex={0}
rowIndex={index}
>
<WebChatListItem
item={chatList[index]}
position={index}
onItemClick={onItemClick}
/>
</CellMeasurer>
)}
overscanRowCount={0}
data={refresh}
/>
{/* {chatList.map(function(item, i) {
return (
<WebChatListItem item={item} position={i} onItemClick={onItemClick} />
);
})} */}
{/* <Button className={classes.btnView}>
<img src={CHAT} className={classes.thumbView} />
</Button> */}
</div>
);
}
Example #11
Source File: WebChatRoomView.js From WhatsApp-Clone with MIT License | 4 votes |
ChatRoomView = ({ chatItem, isNewChat }) => {
const [chatRoomList, setChatRoomList] = useState([]);
const [userId, setUserId] = useState("");
const [refresh, setRefresh] = useState(false);
const [roomId, setRoomId] = useState("");
const [height, setHeight] = useState(80);
const [message, setMessage] = useState("");
const flatList = useRef();
const inputRef = useRef();
const cache = new CellMeasurerCache({
fixedWidth: true,
defaultHeight: 80,
});
// This side effect is for refreshing socket data
useEffect(() => {
if (message != "") {
renderChats();
}
}, [message]);
// This side effect is for refreshing various chat users
useEffect(() => {
if (chatItem != "") {
fetchChatRoomMessages();
// setRefresh(!refresh);
}
}, [chatItem]);
// This side effect is for geting userid first
useEffect(() => {
getUser();
listenSocket([]);
}, [refresh]);
// When user id is retrived this side effect is invoked
useEffect(() => {
fetchChatRoomMessages();
}, [userId]);
function fetchChatRoomMessages() {
let req = {
roomId: chatItem.roomId,
userId: userId,
};
getChatRoom(req)
.then((res) => {
// console.log('RESPONSE => ' + JSON.stringify(res.data));
if (res.status === 200 && res.data && res.data.data.length > 0) {
var chatArray = res.data.data[0].chat;
// chatArray.reverse(); // In case of web reverse is not required
setChatRoomList(chatArray);
} else {
setChatRoomList([]);
}
})
.catch((error) => {
console.log("ERROR ", error);
setChatRoomList([]);
});
}
function getUser() {
const userId = getLocalData(webConstants.USER_ID);
setUserId(userId);
}
function listenSocket() {
socket.removeListener(webConstants.CHAT_ROOM);
socket.on(webConstants.CHAT_ROOM, (message) => {
console.log("Message ROOM Received => ", JSON.stringify(message));
setMessage(message);
});
}
function renderChats() {
// If message received invloves user then only add to list else ignore
if (message.userId === userId || message.chatId === userId) {
setRefresh(true);
if (!chatRoomList) {
chatRoomList = [];
}
setVirtualData(chatRoomList, message);
setTimeout(() => {
setRefresh(false);
}, 1000);
}
}
function setVirtualData(chatArray, message) {
// chatArray.reverse();
message != "" && chatArray.push(message.chat);
// message != "" && chatArray.reverse();
setChatRoomList(chatArray);
flatList.current.forceUpdate();
// flatList.current.scrollToRow(chatArray.length);
// flatList.current.measureAllRows()
setTimeout(() => {
flatList.current.measureAllRows();
flatList.current.scrollToRow(chatArray.length);
}, 1500);
}
const onSendMessage = (text) => {
if (text != "") {
// var chatId = chatItem.chatId;
// if (isNewChat) {
// chatId = chatItem.chatId;
// } else {
// const userType = getUserTypeChatRoom(chatItem, userId);
// const mChatId =
// userType === webConstants.OWNER ? chatItem.chatId : chatItem.userId;
// const mUserId =
// userType === webConstants.OWNER ? chatItem.userId : chatItem.chatId;
// isNewChat = chatRoomList.length === 0 ? true : false;
// const chatRequest = {
// isNewChat: isNewChat,
// roomId: chatItem.roomId,
// userId: chatItem.userId,
// chatId: chatItem.chatId,
// chat: {
// userId: mUserId,
// userName: chatItem.chat[0].userName,
// chatId: mChatId,
// chatName: chatItem.chat[0].chatName,
// chatMessage: text,
// chatNumber: chatItem.chat[0].chatNumber,
// chatImage: chatItem.chat[0].chatImage,
// chatTime: moment().format(),
// chatDelivery: 0,
// chatUnreadCount: 0
// }
// };
// console.log('CHAT chatItem => ', JSON.stringify(chatItem));
// console.log('CHAT MESSAGE => ', JSON.stringify(chatRequest));
isNewChat = chatRoomList.length === 0 ? true : false;
let chatRequest = getChatRoomChatModel(chatItem, isNewChat, userId, text);
socket.emit(webConstants.CHAT_ROOM, chatRequest);
chatRequest.chatUnreadCount = {
userId: userId,
type: "add",
count: 1,
};
if (chatRequest.roomId === "") {
chatRequest.roomId = roomId;
}
const res = isNewChat
? createChatRoom(chatRequest)
: updateChatRoom(chatRequest);
res
.then((res) => {
console.log("CHAT ROOM RESPONSE=> ", JSON.stringify(res));
chatRequest.roomId = res.data.id;
setRoomId(chatRequest.roomId);
// chatRequest.chat.chatUnreadCount = chatRequest.chat.chatUnreadCount + 1;
// chatRequest.chatUnreadCount = {
// userId : userId,
// type: "add",
// count: 1
// };
socket.emit(webConstants.CHAT_LIST, chatRequest);
})
.catch((err) => {
console.log("CHAT ROOM ERROR => ", JSON.stringify(err));
});
}
};
function modifyRowHeight(event) {
if (event.target.value != "") {
setHeight(inputRef.current.clientHeight);
if (chatRoomList.length > 0) {
setTimeout(() => {
flatList.current.measureAllRows();
}, 1500);
flatList.current.scrollToRow(chatRoomList.length);
}
} else {
setTimeout(() => {
setHeight(inputRef.current.clientHeight);
flatList.current.measureAllRows();
flatList.current.scrollToRow(chatRoomList.length);
}, 200);
}
}
const rowRenderer = ({ index, parent, key, style, isScrolling }) => {
var item = chatRoomList[index];
let userType = getUserTypeChatRoom(item, userId);
if (userType === webConstants.OWNER) {
// if (isScrolling) {
// return null;
// }
return (
<CellMeasurer
key={key}
cache={cache}
parent={parent}
columnIndex={0}
rowIndex={index}
>
<ChatRoomRightItem item={item} styleList={style} />
</CellMeasurer>
);
} else {
return (
<CellMeasurer
key={key}
cache={cache}
parent={parent}
columnIndex={0}
rowIndex={index}
>
<ChatRoomLeftItem item={item} styleList={style} />
</CellMeasurer>
);
}
};
return (
<div
style={{
display: "flex",
flexDirection: "column",
width: "100%",
background: "url(" + WhatsapBG + ")",
height: "92%",
}}
>
<div
style={{
backgroundColor: "#E4DDD6",
height: "100%",
zIndex: "100",
opacity: "0.95",
}}
/>
{/* <div
style={{
background: "url(" + WhatsapBG + ")",
width: "100%",
height: "90%"
}}
> */}
<div
style={{
position: "absolute",
zIndex: "1000",
height: "92%",
width: "70%",
}}
>
<List
ref={flatList}
style={{
height: "100%",
width: "100%",
outline: "none",
paddingBottom: height === "" ? 80 : height,
paddingTop: 10,
}}
rowCount={chatRoomList.length}
height={window.innerHeight - 120}
width={window.innerWidth - window.innerWidth / 3.2}
rowHeight={cache.rowHeight}
deferredMeasurementCache={cache}
rowRenderer={rowRenderer}
scrollToAlignment={"end"}
data={refresh}
/>
</div>
<div
ref={inputRef}
style={{
position: "fixed",
zIndex: "2000",
width: "70%",
marginBottom: 0,
resize: "vertical",
bottom: 0,
maxHeight: 160,
minHeight: 60,
overflow: "hidden",
}}
>
<ChatTextInput
onSendMessage={(text) => onSendMessage(text)}
onTyping={(event) => {
modifyRowHeight(event);
}}
/>
</div>
</div>
);
function renderRow(item) {
let userType = getUserTypeChatRoom(item, userId);
if (userType === webConstants.OWNER) {
return <ChatRoomRightItem item={item} />;
} else {
return <ChatRoomLeftItem item={item} />;
}
}
}
Example #12
Source File: WebContactsView.js From WhatsApp-Clone with MIT License | 4 votes |
WebContactsView = ({ onChatCloseClick, onItemClick }) => {
const [contacts, setContacts] = useState([]);
useEffect(() => {
getRegisteredUsers();
}, []);
const getRegisteredUsers = () => {
getLoggedInUserList()
.then(async (res) => {
console.log("User List Response => ", res.data);
if (res.data.success) {
var userList = res.data.data;
var ownerID = await getLocalData(webConstants.USER_ID);
for (let index = 0; index < userList.length; index++) {
const user = userList[index];
if (user.userId === ownerID) {
userList.splice(index, 1);
}
}
setContacts(userList);
}
})
.catch((err) => {
console.log("User List Error => ", err);
});
};
return (
<div style={styles.parent}>
<ContactsHeaderView
item={contacts ? contacts.length : 0}
onChatCloseClick={onChatCloseClick}
/>
<div style={styles.parent} >
{contacts.length <= 0 && <EmptyComponent message={"No User Found"} />}
{contacts.length > 0 && (
<List
style={{
outline: "none",
height: window.innerHeight - 120,
}}
rowCount={contacts.length}
height={window.innerHeight}
width={window.innerWidth}
rowHeight={cache.rowHeight}
rowRenderer={({ index, parent, key, style }) => (
<CellMeasurer
key={key}
cache={cache}
parent={parent}
columnIndex={0}
rowIndex={index}
>
<ContactsItem
item={contacts[index]}
onItemClick={onItemClick}
/>
</CellMeasurer>
)}
overscanRowCount={0}
// data={refresh}
/>
)}
</div>
{/* <FlatList
// contentContainerStyle={DEFAULT_STYLES.container}
data={contacts}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={() => {
return <Divider />;
}}
renderItem={({ item }) => {
return <ContactsItem item={item} navigation={navigation} />;
}}
/> */}
</div>
);
}
Example #13
Source File: WebStatusView.js From WhatsApp-Clone with MIT License | 4 votes |
WebStatusView = ({ onCancelClick }) => {
var [state, dispatch] = useReducer(statusReducer, statusState);
var { statusData, masterStatusList, selectedStatus } = state;
const [refresh, setRefresh] = useState(false);
useEffect(() => {
getUserStatusFromAPI(dispatch);
listenSocket();
}, []);
useEffect(() => {
console.log("masterStatusList : ", masterStatusList.length);
setRefresh(!refresh);
}, [masterStatusList, selectedStatus]);
function toggleStatusView() {
setRefresh(!refresh);
getUserStatusFromAPI(dispatch);
dispatch({ type: SELECTED_STATUS, payload: "" });
}
function listenSocket() {
// socket.removeListener(webConstants.CHAT_LIST);
socket.on(webConstants.USER_STATUS, async (statusModel) => {
const id = getLocalData(webConstants.USER_ID);
if (statusModel.userId != id) {
console.log("STATUS RECEIVED");
getUserStatusFromAPI(dispatch);
}
});
}
return (
<div style={styles.parent}>
<div style={styles.statusView}>
<div style={styles.statusDivView}>
<WebMyStatusView statusData={statusData} isUser dispatch={dispatch} isBorder={false} />
<List
style={{
// height: window.innerHeight,
// width: window.innerWidth,
// paddingTop: "4%",
outline: "none",
}}
// rowCount={40}
rowCount={masterStatusList.length}
height={window.innerHeight - 102}
width={window.innerWidth / 3.5}
rowHeight={statusCache.rowHeight}
rowRenderer={({ index, parent, key, style }) => (
<CellMeasurer
key={key}
cache={statusCache}
parent={parent}
columnIndex={0}
rowIndex={index}
>
{getStatusView({
index,
parent,
key,
style,
masterStatusList,
dispatch,
})}
</CellMeasurer>
)}
overscanRowCount={3}
data={refresh}
/>
</div>
</div>
{(!selectedStatus || selectedStatus === "") && (
<div style={styles.statusDetailView}>
{!statusData && (
<WebStatusEmptyComponent
message={"Click on a contact to view their status updates"}
onCancelClick={onCancelClick}
/>
)}
{statusData && (
<WebZoneStatusComponent
statusData={statusData}
onCancelClick={onCancelClick}
dispatch={dispatch}
/>
)}
</div>
)}
<Animated
animationIn="fadeIn"
animationOut="fadeOut"
animationInDuration={600}
animationOutDuration={1000}
isVisible={selectedStatus && selectedStatus != ""}
animateOnMount={selectedStatus && selectedStatus != ""}
style={{
width: "100%",
position: "absolute",
height: "100%",
zIndex: 500000,
}}
>
{selectedStatus && selectedStatus != "" && (
<div style={styles.statusDetailProgres}>
<WebStatusProgressView
statusData={selectedStatus ? selectedStatus : statusData}
isUser={false}
dispatch={dispatch}
toggleStatusView={toggleStatusView}
/>
</div>
)}
</Animated>
</div>
);
}