Currently, I am developing a chat application with React 18 for its user interface.
The app includes a sidebar that displays user profiles. To ensure the app fits within the browser window height, I've made the list of user profiles scrollable when necessary.
https://i.sstatic.net/XWXq7.png
To achieve this functionality, I have utilized React-Perfect-Scrollbar
in the UsersList.jsx
file which can be found on NPM:
import './_usersList.css';
import axios from 'axios';
import PerfectScrollbar from 'react-perfect-scrollbar';
import { useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
export default function UsersList() {
const API_URL = 'https://randomuser.me/api';
const location = useLocation();
const [users, setUsers] = useState([]);
const getUsers = async () => {
const { data: { results } } = await axios.get(`${API_URL}/?&results=20&inc=id,name,email,picture`, {
});
setUsers(results);
}
const usersList = () => {
return users.map(user => (
<li className="d-table-row w-100">
<div className="user-image-container d-table-cell">
<img src={user.picture.thumbnail} alt={`user.name.first user.name.last`} className="rounded-circle" />
</div>
<div className="text d-table-cell">
<h3 className="display-name m-0">{user.name.first} {user.name.last}</h3>
</div>
</li>
))
}
useEffect(() => {
getUsers();
}, [location])
return (
<div className="chat-users">
<PerfectScrollbar>
<ul className="users-list list-unstyled m-0 d-table w-100">
{ usersList() }
</ul>
</PerfectScrollbar>
</div>
);
}
In the _usersList.css
file, instead of setting a fixed height for the
<div className="chat-users">
, I have specified:
.chat-users {
position: relative;
flex: 1;
}
This allows the element to expand to occupy all available space.
However, an issue arises where the scrollbar is not visible unless a fixed height in pixels (e.g. height: 400px;
) is defined for the element, even if scrolling is required.
The problem is resolved for mobile devices by adding overflow-y: auto
like so:
.chat-users {
position: relative;
flex: 1;
overflow-y: auto;
}
Nevertheless, the problem persists on desktops.
If you want to explore the code further, there's a sandbox available here.