Choppy height CSSTransition in react with multiple items - css

Goal: I'm getting really frustrated and have been scavenging through posts for hours now and can't find any real solution. I'm trying to animation a table row's height to expand/collapse when clicked on. I figured there should be an easy enough solution... Boy was I wrong.
Ideally since each row is going to store quite a bit of extra data, I'd like to load in the data, expand that single row, then remove the data when it's collapsed.
Problem:
I managed to get the animation working great!! I was so excited, only to find out that when I have more than ~3 rows, it gets extremely choppy/laggy. I can't find any fix what so ever.
Here is a sandbox https://codesandbox.io/s/0ql5vp13qv or if you wanted to see the code that manages the animation my code now:
import React, { Component } from 'react'
import { CSSTransition } from 'react-transition-group';
import Icon2 from '../Icon';
import * as Styled from './styles'
export default class CourseRow extends Component {
state = {switched: false};
selectCourse = () => {
this.setState(({switched}) => ({switched: !switched}));
}
render() {
return (
<Styled.Row onClick={this.selectCourse}>
<Styled.InnerRow>
<Styled.Field light>CSCI 1000</Styled.Field>
<Styled.Field>Computer Science 1</Styled.Field>
<Styled.Field>Explore algorithms and data structures that...</Styled.Field>
<Styled.Field><Styled.DropdownButton ><Icon2 icon="up_arrow"/></Styled.DropdownButton></Styled.Field>
</Styled.InnerRow>
<CSSTransition
classNames="fade"
timeout={300}
key={this.props.Title}
in={this.state.switched}
unmountOnExit
>
<div>
test<br/>test<br/>test<br/>
</div>
</CSSTransition>
</Styled.Row>
);
}
}
import styled from 'styled-components';
import Button from 'components/Button';
const columns = "1.5fr 2.5fr 5fr 3fr";
export const DropdownButton = styled(Button)`
background-color: blue;
`;
export const InnerRow = styled.div`
display: grid;
grid-template-columns: ${columns};
grid-column-gap: 1rem;
grid-row-gap: 0;
padding-top: ${props => props.heading ? '2.25rem' : '1.5rem'};
padding-bottom: ${props => props.heading ? '2rem' : '1.5rem'};
padding-left: 0.75rem;
padding-right: 0.75rem;
border-top: ${props => props.heading ? 'none' : '1px solid #E8E8E8'};
cursor: ${props => props.heading ? 'default' : 'pointer'};
`;
export const Row = styled.div`
&:hover {
background-color: #f7faff;
color: #1873EA;
}
& .fade-enter {
overflow-y: hidden;
max-height: 0;
}
& .fade-enter-active {
max-height: 200px;
transition: all 200ms ease;
}
& .fade-exit {
max-height: 200px;
}
& .fade-exit-active {
max-height: 0;
overflow-y: hidden;
transition: all 200ms ease;
}
`;
export const Field = styled.span`
display: flex;
align-items: center;
font-size: 14px;
font-weight: ${props => props.light ? '400' : '300'};
&:last-of-type {
justify-content: flex-end;
}
`;
I thought maybe adding key's to the elements/transitions would help however still nothing...
I took videos of the comparisons so you can see what I'm talking about it.
This is with 1 row:
https://www.youtube.com/watch?v=E6Db7nuqlgk&feature=youtu.be
This is with ~6 rows:
https://www.youtube.com/watch?v=Troba8eIqKA&feature=youtu.be

Related

MUI specificity is different in storybook than in application

I noticed that my styles on a component look right in storybook but not in the running application. The component code is at the bottom of this post.
All the components are from MUI, and looking at the "Computed" tab of the Chrome inspector, I can see that the Avatar components are getting their styles differently in the two environments -- the priorities of the classes are swapped:
In the app:
In the storybook
Wrapping the styles in && fixes the problem, and I've used this solution before for MUI style issues, but I've never come across the case where it behaves differently in the app vs storybook.
Here's my main decorator in preview.tsx
export const decorators: ComponentStoryObj<React.FC>['decorators'] = [
story => {
return (
<>
<header>
<link
href='https://fonts.googleapis.com/css?family=Roboto:100,200,300,400,500,600,700'
rel='stylesheet'
/>
<link
href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,500,600,700'
rel='stylesheet'
/>
</header>
<AppWrapperWithUser>{story()}</AppWrapperWithUser>
</>
);
},
];
Here's the AppWrapper used above, which also wraps the application itself (so that the styles match)
import { ThemeProvider as MuiThemeProvider } from '#mui/material/styles';
import { ThemeProvider as StyledThemeProvider } from 'styled-components';
import { globalStyles, theme } from './theme';
type Props = {
store?: ReturnType<typeof createStore>;
initialState?: RootState;
};
export const AppWrapper: React.FC<Props> = ({ children, store, initialState }) => {
const appStore = store || createStore(initialState);
return (
<MuiThemeProvider theme={theme}>
<StyledThemeProvider theme={theme}>
{globalStyles}
<Provider store={appStore}>{children}</Provider>
</StyledThemeProvider>
</MuiThemeProvider>
);
};
And the component in question:
const S = {
Wrapper: styled(Paper)`
padding: 32px;
display: flex;
justify-content: space-between;
align-items: center;
position: relative;Ø
overflow: hidden;
`,
Pane: styled.div<{ centered?: boolean }>`
display: flex;
flex-direction: column;
gap: 4px;
align-items: ${p => p.centered && 'center'};
`,
Subtitle: styled(Typography).attrs({ variant: 'body2' })`
font-size: 14px;
text-transform: uppercase;
`,
Title: styled(Typography)`
&& {
font-size: 28px;
font-weight: 700;
}
`,
Avatar: styled(Avatar)`
height: 84px;
width: 84px;
box-sizing: content-box;
border: 2px solid rgba(0, 0, 0, 0.1);
`,
TeamLogoWrapper: styled.div`
display: flex;
align-items: center;
height: 100%;
width: 222px;
`,
TeamLogo: styled(Avatar)`
height: 222px;
width: 222px;
box-sizing: content-box;
opacity: 0.3;
border: 2px solid rgba(0, 0, 0, 0.1);
position: absolute;
`,
};
const PlayerDetailHeader = ({ player }: { player: ProcessedPropUIPlayer }) => {
const { ... } = player;
const infoStr = [teamName, `#${uniformNumber}`, position].join(' | ');
return (
<S.Wrapper data-testid={`PlayerDetailHeader-${playerId}`}>
<S.Avatar alt={playerName} src={playerImg} />
<S.Pane>
<S.Title>{playerName}</S.Title>
<S.Subtitle>{infoStr}</S.Subtitle>
</S.Pane>
<S.Pane centered>
<S.Title>{openProps}</S.Title>
<S.Subtitle>Open Props</S.Subtitle>
</S.Pane>
<S.Pane centered>
<S.Title>{dollarFormatter(openAction)}</S.Title>
<S.Subtitle>Open Action</S.Subtitle>
</S.Pane>
<S.TeamLogoWrapper>
<S.TeamLogo alt={teamName} src={teamImg} />
</S.TeamLogoWrapper>
</S.Wrapper>
);
};

scrolling for overflow-x not working properly

I can scroll on the x axis only by moving the laptop touchpad right to left or by pressing in the scroll button and then moving right to left.Not with normal scroll.
the css is the following:
.row {
color: white;
margin-left: 20px;
}
.row__posters {
display: flex;
overflow-y: hidden;
overflow-x: scroll;
padding: 20px;
}
.row__posters::-webkit-scrollbar {
display: none;
}
.row__poster {
object-fit: contain;
width : 100%;
max-height: 100px;
margin-right: 10px;
transition: transform 450ms;
}
.row__poster:hover {
transform: scale(1.08);
}
.row__posterLarge {
max-height: 250px;
}
.row__posterLarge:hover {
transform: scale(1.09);
}
the Javascipt file is:
import React,{ useState , useEffect} from 'react'
import axios from './axios';
import './Row.css';
const base_url = "https://image.tmdb.org/t/p/original/";
function Row({ title ,fetchUrl,isLargeRow }) {
const [movies, setMovies] = useState([]);
// A snippet of code which runs based on a specific condition
useEffect(() => {
// if we leave the brackets blank [] ,run once when the row loads
and dont run again
async function fetchData() {
const request = await axios.get(fetchUrl);
setMovies(request.data.results);
return request;
}
fetchData();
}, [fetchUrl]);
return (
<div className="row">
<h2>{title}</h2>
<div className="row__posters">
{/* several row_posters */}
{movies.map(movie => (
<img
key={movie.id}
className={`row__poster ${isLargeRow && "row__posterLarge"}`}
src={`${base_url}${
isLargeRow ? movie.poster_path : movie.backdrop_path
}`}
alt={movie.name}
/>
))}
</div>
</div>
)
}
export default Row
I tried alot of solutions but I must be doing something wrong because nothing worked .it could be that I used the proposed code in the wrong department.
Thank you for the help in advance!!

How to make dropdown animation?

I am implementing drop-down list using styled-component in react. In the process, I have two questions.
First, when dropDownVisible changes from true to false, why doesn't the animation effect apply and it disappears immediately? How can I improve the animation effect? Like when this list goes down, I want to make it gradually when it goes up.
Second, when StyledDropdown is dropped down, I want it to drop down behind the StyledHead, so I set the z-index property like that. I want the StyledHead to be always on top, so I'm curious why the StyledHead is hidden as the StyledDropdown drops down, even though I gave the z-index property bigger.
The source code is roughly structured like this:
// AApage.jsx
import { useEffect, useState, useRef } from 'react';
import { MdArrowDropDown, MdArrowDropUp } from 'react-icons/md';
import styled, { keyframes } from 'styled-components';
const dropAnimation = keyframes`
0% {
transform : translateY(-300px);
display : none;
}
100% {
transform : translateY(0);
}
`;
const StyledHead = styled.div`
width: 100px;
height: 100px;
background-color: red;
z-index: 11;
`;
const StyledDropdown = styled.div`
width: 100px;
height: 300px;
background-color: #d9d9d9;
border-radius: 0px 0px 10px 10px;
z-index: 3;
animation: ${dropAnimation} 1s alternate;
`;
const AApage = () => {
const [dropDownVisible, setDropDownVisible] = useState<boolean>(false);
const toggleDropDownVisible = () => {
setDropDownVisible((prev) => !prev);
};
return (
<>
<StyledHead>
<div>Dropdown</div>
<span>{`${dropDownVisible}`}</span>
{dropDownVisible ? (
<MdArrowDropUp
onClick={() => {
toggleDropDownVisible();
}}
></MdArrowDropUp>
) : (
<MdArrowDropDown
onClick={() => {
toggleDropDownVisible();
}}
></MdArrowDropDown>
)}
</StyledHead>
{dropDownVisible ? (
<StyledDropdown>
<div>temp data</div>
<div>temp data</div>
<div>temp data</div>
</StyledDropdown>
) : (
<></>
)}
</>
);
};
export default AApage;

React - how to stop div onClick from changing sibling divs

I have 6 div elements that I want to be able to click one of and have the className change for just the div I've clicked on. Currently, when I click on one div, ALL the div classNames change. This idea came from a vanilla JS concept that I'm trying to convert into a React component. I'm not sure where/what is going wrong, if anyone can tell me how to prevent the sibling divs' onClicks from being fired or if what I have is wrong fundamentally, I would be eternally grateful. This is what I have so far:
import React, { useState} from "react";
import { Panels } from "../../components/index";
import { data } from "../../constants/index";
import "./gallery.css";
const Gallery = () => {
const [isOpen, setIsOpen] = useState(false);
const toggleOpen = () => {
setIsOpen(!isOpen);
};
return (
<div className="panels">
{data.restaurants.map((restaurant, index) => (
<div
className={`panel panel${index} ${isOpen ? "open open-active" : ""}`}
onClick={toggleOpen}
>
<Panels
key={restaurant.name + index}
description={restaurant.description}
name={restaurant.name}
website={restaurant.website}
/>
</div>
))}
</div>
);
};
export default Gallery;
This is my Panels Component code:
import React from "react";
const Panels = ({ name, description, website }) => {
return (
<div className="panel_text">
<p>{description}</p>
<p>{name}</p>
<a href={website}>
<p>Visit {name}</p>
</a>
</div>
)};
export default Panels;
Aaaand this is my CSS code:
*, *:before, *:after {
box-sizing: inherit;
}
.panels {
min-height: 100vh;
overflow: hidden;
display: flex;
}
.panel, .panel_text {
background: '#fff';
box-shadow: inse 0 0 0 5px rgba(255, 255, 255, 0.1);
color: var(--color-golden);
text-align: center;
align-items: center;
transition:
font-size 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11),
flex 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11);
font-size: 20px;
background-size: cover;
background-position: center;
flex: 1;
justify-content: center;
display: flex;
flex-direction: column;
}
.panel0 {background-image: url(../../assets/defuegocarousel.jpg);}
.panel1 {background-image: url(../../assets/HaydenslakeSz.jpg);}
.panel2 {background-image: url(../../assets/stonecliffSz.jpg);}
.panel3 {background-image: url(../../assets/shigezooutside.png);}
.panel4 {background-image: url(../../assets/southparkSz.jpeg);}
.panel5 {background-image: url(../../assets/lechonoutside.jpg);}
.panel > * {
margin: 0;
width: 100%;
transition: transform 0.5s;
flex: 1 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.panel > *:first-child {transform: translateY(-100%);}
.panel.open-active > *:first-child {transform: translateY(0); }
.panel > *:last-child { transform: translateY(100%); }
.panel.open-active > *:last-child {transform: translateY(0); }
.panel_text p, a {
text-transform: uppercase;
}
.panel p:nth-child(2) {
font-size: 4rem;
}
.panel.open {
flex: 5;
font-size: 40px;
}
#media only screen and (max-width: 600px) {
.panel p {
font-size: 1rem;
}
}
You're saving a boolean value as a div element is open or not. So this value is considered for all div element's because there is no identifier which div element is open. You need to save a div element value to identify the open div element.
So you can use a div element's index instead of a boolean value. For example, try the below code.
import React, { useState} from "react";
import { Panels } from "../../components/index";
import { data } from "../../constants/index";
import "./gallery.css";
const Gallery = () => {
const [isOpen, setIsOpen] = useState(null);
return (
<div className="panels">
{data.restaurants.map((restaurant, index) => (
<div
className={`panel panel${index} ${isOpen === index ? "open open-active" : ""}`}
onClick={() => setIsOpen(index)}
>
<Panels
key={restaurant.name + index}
description={restaurant.description}
name={restaurant.name}
website={restaurant.website}
/>
</div>
))}
</div>
);
};
export default Gallery;
your isOpen state is common between all your div's
you should specify a unique value for isOpen of each div
you can change your isOpen state to an object like this :
import React, { useState} from "react";
import { Panels } from "../../components/index";
import { data } from "../../constants/index";
import "./gallery.css";
const Gallery = () => {
const [isOpen, setIsOpen] = useState({});
const toggleOpen = (index) => {
setIsOpen(prevState => {...prevState ,[index]:!(!!prevState[index]) });
};
return (
<div className="panels">
{data.restaurants.map((restaurant, index) => (
<div
className={`panel panel${index} ${isOpen[index] ? "open open-active" : ""}`}
onClick={()=>toggleOpen(index)}
>
<Panels
key={restaurant.name + index}
description={restaurant.description}
name={restaurant.name}
website={restaurant.website}
/>
</div>
))}
</div>
);
};
export default Gallery;

CSS Animation not properly working in React App

So I'm trying to make a simple dice roller and want to add a spin animation to make it look cool. For some reason, the animation only works on the initial roll, and not on any after that (unless I refresh). Here is what I have:
App.tsx
export default function App() {
const [dice, setDice] = useState<string[]>([]);
return (
<div className="container">
<h1 className="title-text">Dice Roller</h1>
<div className="roll-dice-button">
<RollBtn setDice={setDice} />
</div>
<Dice dice={dice} />
</div>
)
}
RollBtn.tsx
type Props = {
setDice: (s: string[]) => void
}
export default function RollBtn({setDice}: Props) {
const roll = () => {
let dice: string[] = []'
for(let i = 0; i < 2; i++) {
dice.push(Math.round(Math.random() * 5 + 1));
}
setDice(dice);
}
return <button onClick={() => roll()}>Roll Dice</button>;
}
Dice.tsx
type Props = {
dice: string[];
}
export default function Dice({ dice }: Props) {
return (
<div className="dice-container">
{dice.map((d, i) => (
<div className="die" key={i}>{d}</div>
))}
</div>
)
}
styles.scss
.dice-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-column-gap: 1em;
justify-items: center;
align-items: center;
.die {
width: 2em;
height: 2em;
background-color: white;
border-radius: 8px;
color: black;
font-weight: 900;
font-size: 2em;
line-height: 2em;
text-align: center;
animation: spin_dice .25s;
}
}
As I previously stated, on the initial roll it will do the animation, but after that, it will just change the numbers within the dice.
So, if the animation is not a loop, it will be executed just once when the component is rendered. So you need to change the class of the div .die for "" and then change it back to .die when you click on the roll button.
For that you should put the RollBtn and Dice in just one component.

Resources