Dynamically setting height of React rendered table in Firefox differs from Chrome - javascript

working on a React project currently, using webpack, webpack-dev-server, hot module reloading, React Router, styled-components etc
I have created a Table component where I try to dynamically determine the number of rows to render within the Table based on the height of the parent. Within Chrome, this works as expected, but in Firefox I am finding that all my rows are being rendered and therefore are not bound within the parent component.
Is this a known issue or are there any suggested workarounds or is there something horrendously wrong with my code?
Parent component (App):
const MainContainer = styled.div`
background-color: ${colours.white};
border-radius: 4px;
box-shadow: 0 0 9px 0 #dedede;
display: flex;
flex-wrap: wrap;
height: 85%;
width: 92.5%;
`;
const InnerContainer = styled.div`
display: flex;
flex-direction: column;
width: calc(100% - 9.375em);
`;
const SearchAndCountPlaceholder = styled.div`
height: 12.5%;
`;
const SidebarPlaceholder = styled.div`
background-color: ${colours.blue.light};
height: 100%;
opacity: 0.12;
width: 9.375em;
`;
const LoadMoreButtonContainerPlaceholder = styled.div`
height: 15%;
`;
const App = () => (
<MainContainer className="app-component">
<SidebarPlaceholder />
<InnerContainer>
<SearchAndCountPlaceholder />
<Table tableHeadings={tableHeadings} masterData={mockData} />
<LoadMoreButtonContainerPlaceholder />
</InnerContainer>
</MainContainer>
);
Table component:
const Container = styled.div`
background-color: ${colours.white};
height: 100%;
overflow-x: scroll;
padding-bottom: 1em;
width: 100%;
`;
const StyledTable = styled.table`
border-bottom: 2px solid ${colours.grey.lighter};
border-collapse: collapse;
margin: 1.25em;
table-layout: fixed;
width: 100%;
& thead {
border-bottom: inherit;
color: ${colours.grey.lighter};
font-size: 0.75em;
font-weight: 700;
line-height: 1em;
text-align: left;
text-transform: uppercase;
& th {
padding: 0.75em 1em 0.75em 1em;
width: 7.25em;
}
& th:not(.Source) {
cursor: pointer;
}
& span {
color: ${colours.blue.dark};
font-size: 1em;
font-weight: 300;
margin-left: 0.313em;
}
}
& tbody {
color: ${colours.grey.dark};
font-size: 0.813em;
line-height: 1.125em;
& tr {
border-bottom: 1px solid ${colours.grey.lightest};
& td {
padding: 1em;
}
}
& .masterData {
font-weight: 700;
}
}
`;
let numberOfRowsToDisplay;
const calculateNumberOfRowsToDisplay = () => {
const tableHeight = document.querySelector('.table-component').offsetHeight;
const rowHeight = 40; // height of row in pixels
const numberOfRowsNotToIncludeInCalculation = 2; // header & scrollbar
numberOfRowsToDisplay = Math.floor(
tableHeight / rowHeight - numberOfRowsNotToIncludeInCalculation
);
};
class Table extends Component {
constructor(props) {
super(props);
this.state = { columnToSort: '' };
this.onColumnSortClick = this.onColumnSortClick.bind(this);
}
componentDidMount() {
calculateNumberOfRowsToDisplay();
}
onColumnSortClick(event) {
event.preventDefault();
const columnToSort = event.target.className;
this.setState(prevState => {
if (prevState.columnToSort === columnToSort) {
return { columnToSort: '' };
}
return { columnToSort };
});
}
render() {
const { tableHeadings, masterData } = this.props;
const { columnToSort } = this.state;
const upArrow = '⬆';
const downArrow = '⬇';
return (
<Container className="table-component">
<StyledTable>
<thead>
<tr>
{tableHeadings.map(heading => (
<th
className={heading}
key={heading}
onClick={this.onColumnSortClick}
>
{heading}{' '}
{heading !== 'Source' ? (
<span>
{heading === columnToSort ? upArrow : downArrow}
</span>
) : null}
</th>
))}
</tr>
</thead>
<tbody>
{masterData &&
masterData.slice(0, numberOfRowsToDisplay).map(data => {
const dataKey = uuidv4();
return (
<tr className="masterData" key={dataKey}>
<td>Master</td>
{Object.values(data).map(datum => {
const datumKey = uuidv4();
return <td key={datumKey}>{datum}</td>;
})}
</tr>
);
})}
</tbody>
</StyledTable>
</Container>
);
}
}
Thanks in advance!

Maybe not the answer I was quite looking for, but in the end I have set the dynamic numberOfRowsToDisplay as part of the component's state; which has given me the UI result I was looking for

Related

Issues with getting the css class to change based off uid from firestore React

I hope you all are doing well. I was following this fireship io tutorial in building a chat app in react. I updated how I got the data with hooks instead of how it was done in the video.
The issue is, I have it working where I can send and receive messages, but I can't apply the appropriate CSS style depending on which user sent a message. The odd part is, I'm able to console log the text and the uid as props.
The focus is on const ChatMessage where, depending on the uid of the current user, it will change the CSS styling to mimic that of imessage. Here's an example.
Final Product
I have it set up where I run npm from vs code and I access the app from two of my google accounts. One from firefox, the other from chrome.
I'm really trying to get a hang of firebase react with hooks, anything helps.
Cheers,
Tutorial Source Code: https://github.com/fireship-io/react-firebase-chat
App.js
import "./App.css";
import "firebase/firestore";
import "firebase/auth";
import { useAuthState } from "react-firebase-hooks/auth";
import { db } from "./firebase";
import {
collection,
onSnapshot,
addDoc,
serverTimestamp,
query,
orderBy,
limit,
} from "firebase/firestore";
import { useEffect, useState, useRef } from "react";
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const provider = new GoogleAuthProvider();
const auth = getAuth();
const userID = "";
function App() {
const [user] = useAuthState(auth);
return (
<div className="App">
<header>
<h1>SUp# Ch#tZ🫡</h1>
<SignOut />
</header>
<section>{user ? <ChatRoom /> : <SignIn />}</section>
</div>
);
}
const ChatRoom = () => {
const [messages, setMessages] = useState([]);
const [formValue, setFormValue] = useState("");
const messagesRef = collection(db, "messages");
const recentMessage = useRef();
const queryAtts = query(messagesRef, orderBy("createdAt"), limit(25));
//Send Messages
const sendMessage = async (e) => {
e.preventDefault();
const { uid, photoURL } = auth.currentUser;
await addDoc(collection(db, "messages"), {
text: formValue,
createdAt: serverTimestamp(),
uid,
photoURL,
});
setFormValue("");
recentMessage.current.scrollIntoView({ behavior: "smooth" });
};
//Get Messages from Firestore
useEffect(() => {
//console.log(messagesRef);
onSnapshot(queryAtts, (snapshot) => {
setMessages(
snapshot.docs.map((doc) => {
return { id: doc.id, viewing: false, ...doc.data() };
})
);
});
}, []);
return (
<>
<main>
{messages &&
messages.map((msg, i) => (
<>
{console.log("Pre-Chat Msg uid: ", msg.uid)}
<ChatMessage
msg={msg.text}
uid={msg.uid}
photoURL={auth.currentUser.photoURL}
/>
</>
))}
<div ref={recentMessage}></div>
</main>
<form onSubmit={sendMessage}>
<input
value={formValue}
onChange={(e) => setFormValue(e.target.value)}
/>
<button type="submit" disabled={!formValue}>
😶‍🌫️
</button>
</form>
</>
);
};
const ChatMessage = (props) => {
//console.log("uid in chat msg: ", props.uid);
console.log("chat message photo: ", props.photoURL);
const messageClass = props.uid === auth.currentUser ? "sent" : "recieved";
console.log("useAuthStateHook uid: ", props.uid);
return (
<div className={`message ${messageClass}`}>
<img
src={
props.photoURL || "https://xsgames.co/randomusers/avatar.php?g=pixel"
}
alt={"broken lol"}
/>
<p key={props.uid}>{props.msg}</p>
</div>
);
};
const SignIn = () => {
const useSignInWithGoogle = () => {
signInWithPopup(auth, provider);
};
return (
<>
<button onClick={useSignInWithGoogle}>SignIn W/ Google</button>
<p>
Do not violate the community guidelines or you will be banned for life!
</p>
</>
);
};
const SignOut = () => {
return (
auth.currentUser && (
<button className="sign-out" onClick={() => auth.signOut()}>
Sign Out
</button>
)
);
};
export default App;
App.css
body {
background-color: #282c34;
}
.App {
text-align: center;
max-width: 728px;
margin: 0 auto;
}
.App header {
background-color: #181717;
height: 10vh;
min-height: 50px;
color: white;
position: fixed;
width: 100%;
max-width: 728px;
top: 0;
display: flex;
align-items: center;
justify-content: space-between;
z-index: 99;
padding: 10px;
box-sizing: border-box;
}
.App section {
display: flex;
flex-direction: column;
justify-content: center;
min-height: 100vh;
background-color: rgb(40, 37, 53);
}
main {
padding: 10px;
height: 80vh;
margin: 10vh 0 10vh;
overflow-y: scroll;
display: flex;
flex-direction: column;
}
main::-webkit-scrollbar {
width: 0.25rem;
}
main::-webkit-scrollbar-track {
background: #1e1e24;
}
main::-webkit-scrollbar-thumb {
background: #6649b8;
}
form {
height: 10vh;
position: fixed;
bottom: 0;
background-color: rgb(24, 23, 23);
width: 100%;
max-width: 728px;
display: flex;
font-size: 1.5rem;
}
form button {
width: 20%;
background-color: rgb(56, 56, 143);
}
input {
line-height: 1.5;
width: 100%;
font-size: 1.5rem;
background: rgb(58, 58, 58);
color: white;
outline: none;
border: none;
padding: 0 10px;
}
button {
background-color: #282c34; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
font-size: 1.25rem;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.sign-in {
color: #282c34;
background: white;
max-width: 400px;
margin: 0 auto;
}
ul, li {
text-align: left;
list-style: none;
}
p {
max-width: 500px;
margin-bottom: 12px;
line-height: 24px;
padding: 10px 20px;
border-radius: 25px;
position: relative;
color: white;
text-align: center;
}
.message {
display: flex;
align-items: center;
}
.sent {
flex-direction: row-reverse;
}
.sent p {
color: white;
background: #0b93f6;
align-self: flex-end;
}
.received p {
background: #e5e5ea;
color: black;
}
img {
width: 40px;
height: 40px;
border-radius: 50%;
margin: 2px 5px;
}
I've tried maneuvering where the auth.currentUser was called. I also reformatted my functions from the function to const format, but I don't believe that makes much of a difference.
It seems that in your ChatMessage component, the messageClass will get a value based on if props.uid equals to uid of the current user.
If this is the goal, you can set it like:
const messageClass = props.uid === auth.currentUser?.uid ? "sent" : "recieved";
Instead of:
const messageClass = props.uid === auth.currentUser ? "sent" : "recieved";
Because auth.currentUser is the object that has some user data properties such as uid.

How to display data from clicked container to other con

Can someone help me to display specific song while clicking on that in Your Playlist container on the left??
I am trying to list data on the left in Your Playlist container When I click on one of the music it should show it in Your Playlist container. It has to save it to browser history as well and it has to remove it from Search because it is already gonna be in Your Playlist container. I will deploy it later to Firebase but now I need help.
It should be added to the left while clicking on one of the listed songs after a search.
Please support me on that.
I am adding my codes here as well for my project:
I have App.js
import "./App.css";
import MySongs from "./MySongs.js";
import Search from "./Search.jsx";
function App() {
return (
<div className="App">
<div className="body">
<MySongs />
<Search />
</div>
</div>
);
}
export default App;
.App {
background-color: #303030;
width: 100%;
height: 100vh;
}
.body {
display: flex;
}
I have Search.jsx
import React, { useState, useEffect, useRef } from "react";
import "./Search.css";
import styled from 'styled-components';
import { IoSearch,IoClose } from "react-icons/io5";
import {motion, AnimatePresence} from "framer-motion";
import {useClickOutside} from "react-click-outside-hook";
import MoonLoader from 'react-spinners/MoonLoader';
import { useDebounce } from "./hooks/debounceHook";
import axios from "axios";
import { TvShow } from "./tvShow";
const SearchBarContainer = styled(motion.div)`
margin-left: 10px;
margin-top: 20px;
display: flex;
flex-direction: column;
width: 96%;
height: 2.5em;
background-color: #424242;
border-radius: 3px;
`;
const SearchInputContainer = styled.div`
width: 98%;
min-height: 2.5em;
display: flex;
align-items: center;
position: relative;
padding: 2px 15px;
`;
const SearchInput = styled.input`
width: 100%;
height: 100%;
outline: none;
border: none;
font-size: 15px;
color: white;
font-weight: 300;
border-radius: 6px;
background-color: transparent;
&:focus {
outline: none;
&::placeholder {
opacity: 0;
}
}
&::placeholder {
color: #white;
transition: all 250ms ease-in-out;
}
`;
const SearchIcon = styled.span`
color: #bebebe;
font-size: 14px;
margin-right: 10px;
margin-top: 6px;
vertical-align: middle;
`;
const CloseIcon = styled(motion.span)`
color: #bebebe;
font-size: 15px;
vertical-align: middle;
transition: all 200ms ease-in-out;
cursor: pointer;
&:hover {
color: #dfdfdf;
}
`;
const LineSeperator = styled.span`
display: flex;
min-width: 100%;
min-height: 2px;
background-color: #d8d8d878;
`;
const SearchContent = styled.div`
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
padding: 1em;
overflow-y: auto;
`;
const LoadingWrapper = styled.div`
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
`;
const WarningMessage = styled.span`
color: #a1a1a1;
font-size: 14px;
display: flex;
align-self: center;
justify-self: center;
`;
const containerVariants = {
expanded: {
height: "26em",
},
collapsed: {
height: "2.5em",
},
};
const containerTransition = { type: "spring", damping: 22, stiffness: 150 };
export function SearchBar(props) {
const [isExpanded, setExpanded] = useState(false);
const [parentRef, isClickedOutside] = useClickOutside();
const inputRef = useRef();
const [searchQuery, setSearchQuery] = useState("");
const [isLoading, setLoading] = useState(false);
const [tvShows, setTvShows] = useState([]);
const [noTvShows, setNoTvShows] = useState(false);
const isEmpty = !tvShows || tvShows.length === 0;
const changeHandler = (e) => {
e.preventDefault();
if (e.target.value.trim() === "") setNoTvShows(false);
setSearchQuery(e.target.value);
};
const expandContainer = () => {
setExpanded(true);
};
const collapseContainer = () => {
setExpanded(false);
setSearchQuery("");
setLoading(false);
setNoTvShows(false);
setTvShows([]);
if (inputRef.current) inputRef.current.value = "";
};
useEffect(() => {
if (isClickedOutside) collapseContainer();
}, [isClickedOutside]);
const searchTvShow = async () => {
if (!searchQuery || searchQuery.trim() === "") return;
setLoading(true);
setNoTvShows(false);
const options = {
method: 'GET',
url: 'https://deezerdevs-deezer.p.rapidapi.com/search',
params: {q: searchQuery},
headers: {
'x-rapidapi-host': 'deezerdevs-deezer.p.rapidapi.com',
'x-rapidapi-key': '6a99d5e101msh1e9f2b2f948746fp1ae1f3jsn6b458fe8b4e4'
}
};
axios.request(options).then(function (response) {
if (response) {
if (response.data && response.data.length === 0) setNoTvShows(true);
setTvShows(response.data.data);
}
}).catch(function (error) {
console.error(error);
});
setLoading(false);
};
useDebounce(searchQuery, 500, searchTvShow);
// console.log(tvShows);
return (
<div className="my__search">
<SearchBarContainer
animate={isExpanded ? "expanded" : "collapsed"}
variants={containerVariants}
transition={containerTransition}
ref={parentRef}
>
<SearchInputContainer>
<SearchIcon>
<IoSearch />
</SearchIcon>
<SearchInput
placeholder="Search for Series/Shows"
onFocus={expandContainer}
ref={inputRef}
value={searchQuery}
onChange={changeHandler}
/>
<AnimatePresence>
{isExpanded && (
<CloseIcon
key="close-icon"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={collapseContainer}
transition={{ duration: 0.2 }}
>
<IoClose />
</CloseIcon>
)}
</AnimatePresence>
</SearchInputContainer>
{isExpanded && <LineSeperator />}
{isExpanded && (
<SearchContent>
{isLoading && (
<LoadingWrapper>
<MoonLoader loading color="#000" size={20} />
</LoadingWrapper>
)}
{!isLoading && isEmpty && !noTvShows && (
<LoadingWrapper>
<WarningMessage>Start typing to Search</WarningMessage>
</LoadingWrapper>
)}
{!isLoading && noTvShows && (
<LoadingWrapper>
<WarningMessage>No Tv Shows or Series found!</WarningMessage>
</LoadingWrapper>
)}
{!isLoading && !isEmpty && (
<>
{tvShows.map((show) => (
<TvShow
key={show.id}
thumbnailSrc={show.album.cover_medium}
name={show.title_short}
artist={show.artist.name}
/>
))}
</>
)}
</SearchContent>
)}
</SearchBarContainer>
</div>
);
}
export default SearchBar;
.my__search {
margin-top: 20px;
flex: 0.6;
height: 450px;
border-radius: 5px;
border: 1px solid black;
margin-left: 80px;
background-color: #424242;
}
I have tvShow.jsx
import React, { useState } from "react";
import styled from "styled-components";
import {ImDownload} from "react-icons/im";
const TvShowContainer = styled.div`
width: 96%%;
min-height: 3em;
display: flex;
border-bottom: 2px solid #555555;
align-items: center;
`;
const Thumbnail = styled.div`
width: auto;
height: 80%;
display: flex;
flex: 0.4;
img {
border-radius: 20px;
width: auto;
height: 100%;
}
`;
const Name = styled.h3`
font-size: 12px;
color: white;
flex: 2;
display: flex;
flex-direction: column;
`;
const Artist = styled.span`
margin-top: 10px;
font-size: 8px;
color: white;
display: flex;
align-items: center;
`;
const Rating = styled.span`
color: #a1a1a1;
font-size: 16px;
display: flex;
flex: 0.2;
`;
export function TvShow(props) {
const { thumbnailSrc, name, artist,clickedMusic } = props;
const [wantedMusic, setWantedMusic] = useState("");
// const [clickedShow, setClickedShow] = useState("");
// function clickedContainer(e){
// const element = e.currentTarget();
// setClickedShow(element);
// console.log("I am clickedShow " +clickedShow);
// }
return (
<TvShowContainer onclick="location.href='#';" >
<Thumbnail>
<img src={thumbnailSrc} />
</Thumbnail>
<Name>{name}
<Artist>
{artist}
</Artist>
</Name>
</TvShowContainer>
);
}
I have mySongs.js
import React from "react";
import "./MySongs.css";
function MySongs() {
return (
<div className="my__songs">
<p>Your Playlist</p>
</div>
);
}
export default MySongs;
.my__songs {
margin-left: 10px;
margin-top: 20px;
flex: 0.3;
height: 300px;
height: 450px;
border: 1px solid black;
border-radius: 5px;
background-color: #424242;
}
.my__songs > p {
color: white;
opacity: 90%;
margin-left: 10px;
font-size: 13px;
}
Only partly answering the question: move an item from one list to another (and back) on mouse click.
The basic situation can be solved if you use the parent component to hold the state that the children components display. Then you only need to implement a function that toggles a "flag" (like selected), and the components can be rendered based on that flag.
const {useState} = React
const tracklist = [
{
id: 1,
title: 'Track 1',
selected: false,
},
{
id: 2,
title: 'Track 2',
selected: false,
},
{
id: 3,
title: 'Track 3',
selected: false,
},
{
id: 4,
title: 'Track 4',
selected: false,
},
{
id: 5,
title: 'Track 5',
selected: false,
},
]
const ListItem = ({ title, onToggleSelect }) => <div className="list-item" onClick={onToggleSelect}>{title}</div>
const App = ({ tracklist }) => {
const [tracks, setTracks] = useState(tracklist)
const toggleSelect = (id) => {
setTracks((prevState) => prevState.map(item => item.id === id ? {...item, selected: !item.selected} : item))
}
const listItem = (track) => <ListItem key={track.id} {...track} onToggleSelect={() => toggleSelect(track.id)}/>
return (
<div className="container" >
<div className="tracklist">
{
tracks
.filter(({ selected }) => selected)
.map(listItem)
}
</div>
<div className="tracklist">
{
tracks
.filter(({ selected }) => !selected)
.map(listItem)
}
</div>
</div>
)
}
ReactDOM.render(
<App tracklist={tracklist} />,
document.getElementById('root')
);
html, body {
margin: 0;
padding: 5px 10px;
}
.container {
display: grid;
grid-template-columns: 1fr 3fr;
gap: 20px;
}
.list-item {
cursor: pointer;
}
.list-item:hover {
background: lightgray;
}
.tracklist {
border: 1px solid gray;
}
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>

fireEvent.Blur() is not working in my custom input component

// Custom Input component
const Container = styled.div``;
const InputBase = styled.div<{ width: string }>`
display: flex;
width: ${(props) => props.width};
height: 42px;
justify-content: space-between;
align-items: center;
padding: 9px 10px;
border-radius: 8px;
border: solid 2px ${color.gray[200]};
background-color: white;
&[data-focus="true"] {
border: solid 2px ${color.gray[300]};
}
&[data-disabled="true"] {
background-color: ${color.background.original};
}
`;
const InputArea = styled.input`
width: 100%;
border: 0;
background-color: inherit;
font-size: 15px;
font-weight: normal;
&:focus {
outline: none;
}
&:disabled {
color: ${color.gray[600]};
}
::placeholder {
color: ${color.gray[600]};
}
`;
const Label = styled.label`
color: ${color.gray[600]};
font-size: 15px;
font-weight: bold;
display: inline-block;
margin-bottom: 10px;
`;
const Input: ForwardRefRenderFunction<HTMLInputElement, Props> = (
{ formWidth = "100%", icon = null, labelText, onFocus, onBlur, ...props },
ref
) => {
const [isFocus, setIsFocus] = useState<boolean>(false);
const handelFocus = (e) => {
setIsFocus(true);
if (onFocus) onFocus(e);
};
const handleBlur = (e) => {
setIsFocus(false);
if (onBlur) onBlur(e);
};
return (
<Container>
{labelText && <Label htmlFor={props.id}>{labelText}</Label>}
<InputBase
data-focus={isFocus}
data-disabled={props.disabled}
width={formWidth}
>
<InputArea
ref={ref}
type="text"
{...props}
onFocus={handelFocus}
onBlur={handleBlur}
/>
{icon}
</InputBase>
</Container>
);
};
export default forwardRef(Input);
I'm making the component into a library and using it in another project.
The code below works normally when testing in the library.
describe("Input", () => {
it("test", async () => {
const handleBlur = jest.fn();
render(
<Input data-testid="input" onBlur={handleBlur} />
);
const input = screen.getByTestId("input") as HTMLInputElement;
fireEvent.change(input, { target: { value: "test" } });
fireEvent.blur(input);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
});
However, in other projects that use that library, fireEvent.blur(input) does not work (toHaveBeenCalledTime is 0) and fireEvent.focusOut(input) does.
Is there something wrong with the library bundling process? Or is there something I'm missing?

create an expand content or show more content button in react app

So i am trying to basically add a expand button to my react app that will reveal more information and i would prefer that the app expand the div size to reveal the additional content, so the its basically an expand button, i understand i need to utilize the usestate property and a function however i am having a hard time figuring out how do i update the css of the student div to expand and reveal the added information. The added information is the grades portion (FYI).
UPDATE: I have found a way to display the changes the problem i am facing is to get the state to start as isExpanded false so when a user clicks the plus button it expands to reveal the class hidden information again
here is my App.js file
import React, { useState } from "react";
import "./App.css";
export default function App() {
const [students, setStudents] = useState(null);
const [filterData, setFilterData ] = useState(null);
const [isExpanded, setIsExpanded] = useState(false);
const studentdata = 'https://www.hatchways.io/api/assessment/students';
function getStudents(){
fetch(studentdata)
.then(resp => resp.json())
.then(data => {
setFilterData(data.students);
setStudents(data.students);
setIsExpanded(false);
})
}
const searchByName = (event) => {
event.persist();
// Get the search term
const searchItem = event.target.value.toLowerCase().trim();
// If search term is empty fill with full students data
if(!searchItem.trim()) {
setFilterData(students);
}
// Search the name and if it found retun the same array
const serachIn = (firstName, lastName) => {
if(firstName.indexOf(searchItem) !== -1 || lastName.indexOf(searchItem) !== -1) {
return true;
}
let fullName = firstName.toLowerCase()+" "+lastName.toLowerCase();
if(fullName.indexOf(searchItem) !== -1) {
return true;
}
return false;
};
// Filter the array
const filteredData = students.filter((item) => {
return serachIn(item.firstName, item.lastName);
});
// Set the state with filtered data
setFilterData(filteredData);
}
function exp() {
if(isExpanded){
setIsExpanded(true);
}
}
return (
<div className="App">
<h1>Students</h1>
<div>
<button className="fetch-button" onClick={getStudents}>
Get Students
</button>
<br />
</div>
<div className="search" id="search">
<input type="text" name="serachByName" id="searchbar" placeholder="Search by name" onChange={(e) => searchByName(e)} ></input>
</div>
{filterData && filterData.map((student, index) => {
var total = 0;
for(var i = 0; i < student.grades.length; i++) {
var grade = parseInt(student.grades[i]);
total += grade;
}
const avg = total / student.grades.length;
const average = avg.toString();
const grade1 = student.grades[0];
const grade2 = student.grades[1];
const grade3 = student.grades[2];
const grade4 = student.grades[3];
const grade5 = student.grades[4];
const grade6 = student.grades[5];
const grade7 = student.grades[6];
const grade8 = student.grades[7];
return(
<div className={'student' + isExpanded ? 'expanded' : '' } key={index}>
<div className="image">
<img src={student.pic} id="icon"></img>
</div>
<div className="text">
<h3 id="name">{student.firstName} {student.lastName}</h3>
<p id="detail"><strong>EMAIL:</strong> {student.email}</p>
<p id="detail"><strong>COMPANY:</strong> {student.company}</p>
<p id="detail"><strong>SKILL:</strong> {student.skill}</p>
<p id="detail"><strong>AVERAGE:</strong>: {average}%</p>
<p id="detail" className="hidden">
<br></br>Test 1 :{grade1}
<br></br>Test 2 :{grade2}
<br></br>Test 3 :{grade3}
<br></br>Test 4 :{grade4}
<br></br>Test 5 :{grade5}
<br></br>Test 6 :{grade6}
<br></br>Test 7 :{grade7}
<br></br>Test 8 :{grade8}
</p>
</div>
<div className="expand">
<button className="expand_btn" onClick={exp()} id="expand_btn">+</button>
</div>
</div>
)}
)}
</div>
);
}
and my css file
#import url('https://fonts.googleapis.com/css?family=Bebas+Neue&display=swap');
#import url('https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap');
.root{
width: 100vw;
height: 100vh;
background-color: black;
}
.App {
text-align: center;
width: 1000px;
height: 750px;
background-color: aliceblue;
border: 4px solid black;
border-radius: 5%;
margin-top: 75px;
margin-left: auto;
margin-right: auto;
overflow: scroll;
}
.student{
width: 80%;
height: 200px;
background-color: white;
display: flex;
align-items: center;
padding-top: 3%;
padding-bottom: 3%;
border: 2px solid lightblue;
margin-left: auto;
margin-right: auto;
}
.text{
text-align: left;
padding-left: 7%;
width: 300px;
}
.image{
padding-left: 15%;
}
#icon{
border-radius: 50%;
width: 150px;
height: 150px;
border: 2px solid black;
}
#name{
text-transform: capitalize;
font-family: 'Bebas Neue';
letter-spacing: 4px;
font-size: 40px;
margin-bottom: 10px;
margin-top: 10px;
}
#detail {
font-family: 'Roboto';
font-weight: 300;
line-height: normal;
margin: 0;
}
.search {
width: 80%;
height: 20px;
margin-left: auto;
margin-right: auto;
margin-top: 10px;
margin-bottom: 20px;
}
#searchbar {
width: 100%;
height: 30px;
font-family: 'Roboto';
font-size: 18px;
font-weight: 300;
}
.expand {
width: 100px;
height: 100px;
padding-left: 3%;
margin-bottom: 5%;
}
#expand_btn {
font-family: 'Bebas Neue';
font-size: 50px;
color: lightskyblue;
background-color: transparent;
border: none;
}
.hidden {
display: none;
}
.expanded{
width: 80%;
height: 300px;
background-color: white;
display: flex;
align-items: center;
padding-top: 3%;
padding-bottom: 3%;
border: 2px solid lightblue;
margin-left: auto;
margin-right: auto;
}
I have fixed the issue in this codesandbox - https://codesandbox.io/s/purple-bird-j5vrm
Check and let me know if this helps.
There are many ways to solve your problem. One way is adding isExpanded flag to each object in the students array so that each student object would know if that is expanded or not. And I have used the flag like this
className={"student " + student.isExpanded ? "expanded" : " "}
As per your implementation, isExpanded was being set globally so every student item would be set as Expanded and there was no way to know which item was expanded.
Note: I have implemented only for getStudents and not filterStudents.

Centering active element inside custom React carousel

I have a simple custom React carousel:
https://codesandbox.io/s/infallible-wood-740s2?fontsize=14
It goes through numbers from 1 to 100. I'm trying to have an active number centered with large font size, and its neighbors with smaller font size:
To progress through this carousel, you have to click on the carousel.
The issue is that progressing through the carousel numbers starts to misalign. I suppose that it is because of the wrong calculation for left property.
I've tried to tweak the formula, use React Transition Group, and find some existing package which could solve this issue, but I haven't succeeded. I would appreciate any help.
Component code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import {
Wrapper,
NumbersWrapper,
NumbersScroller,
NumberText
} from "./Numbers.style";
const hundred = new Array(100)
.fill(0)
.map((k, v) => ({ key: v, label: v + 1 }));
class Numbers extends Component {
constructor(props) {
super(props);
this.state = {
activeNumber: 0
};
}
setActiveNumber(number) {
this.setState({
activeNumber: number
});
}
render() {
const { activeNumber } = this.state;
const intAciveNumber = Number(activeNumber);
return (
<Wrapper>
<NumbersWrapper
onClick={() => this.setActiveNumber(intAciveNumber + 1)}
>
<NumbersScroller
style={{
left: `${130 - intAciveNumber * 55}px`
}}
>
{hundred.map(({ key, label }) => {
const isNeighbor =
key + 1 === activeNumber || key - 1 === activeNumber;
const isActive = key === activeNumber;
return (
<NumberText
key={key}
isNeighbor={isNeighbor}
isActive={isActive}
>
{label}
</NumberText>
);
})}
</NumbersScroller>
</NumbersWrapper>
</Wrapper>
);
}
}
export default Numbers;
const rootElement = document.getElementById("root");
ReactDOM.render(<Numbers />, rootElement);
Numbers.style.js:
import styled from "styled-components";
export const Wrapper = styled.div`
height: 549px;
width: 612px;
border-radius: 28px;
background-color: #ffffff;
margin-top: 116px;
padding: 26px 0 0 0;
display: flex;
flex-direction: column;
align-items: center;
position: absolute;
left: 50%;
top: 0%;
transform: translate(-50%, -10%);
overflow: hidden;
`;
export const NumbersWrapper = styled.div`
white-space: nowrap;
width: 359.5px;
overflow: hidden;
`;
export const NumbersScroller = styled.div`
transition: all 150ms ease-in;
position: relative;
left: 130px;
`;
const numberTextStyle = props => {
if (props.isNeighbor) {
return `
height: 88px;
width: 53px;
opacity: 0.45;
color: #6C879C;
font-size: 80px;
font-weight: 300;
letter-spacing: -1.6px;
line-height: 88px;
text-align: center;
`;
}
if (props.isActive) {
return `
height: 156px;
color: #6C879C;
font-size: 150px;
font-weight: 300;
letter-spacing: -3px;
line-height: 156px;
text-align: center;
`;
}
return `
opacity: 0.2;
color: #6C879C;
font-size: 40px;
font-weight: 300;
letter-spacing: -0.8px;
line-height: 48px;
text-align: center;
`;
};
export const NumberText = styled.span`
font-family: Avenir;
margin: 0 15px;
user-select: none;
&:first-child {
margin-left: 0;
}
&:last-child {
margin-right: 0;
}
${props => numberTextStyle(props)}
`;

Categories

Resources