How can i keep my changes after not Intersecting to my element? - reactjs

I'm using react and I want to make some animation when the viewport is on my desired element,
but I only want to fire it once so when observer value is false, my element style not changing again to beginning .
I'm using styled-components for styling
HomeSection.Projects = function HomeSectionProjects({ children, ...rest }) {
const ref = useRef(null);
const [isVisible, setVisible] = useState(false);
const callbackFn = (entries) => {
const [entry] = entries;
setVisible(entry.isIntersecting);
};
useEffect(() => {
const options = {
root: null,
rootMargin: "0px",
threshold: 1,
};
const observer = new IntersectionObserver(callbackFn, options);
if (ref.current) observer.observe(ref.current);
}, [ref]);
return <Projects ref={ref}>{children}</Projects>;
};
So here is my styled-comp
export const Projects = styled.div`
width: 70%;
height: 70vh;
display: flex;
opacity: 1;
margin-bottom: 30vh;
justify-content: flex-start;
align-items: center;
position: relative;
transition: opacity 1.5s ease-out;
#media screen and (max-width: 763px) {
margin-bottom: 20%;
height: 50vh;
align-items: center;
flex-direction: column;
padding-top: 10%;
width: 100%;
}
&:hover ${ImageDiv} {
transform: scale(0.9);
}
&:hover ${Title} {
/* transform: scale(1.4); */
font-size: 8rem;
#media screen and (max-width: 763px) {
font-size: 3.2rem;
}
}
&:hover ${TitleInfo} {
font-size: 2rem;
bottom: -5%;
#media screen and (max-width: 763px) {
font-size: 1.5rem;
}
}
&:hover ${Info} {
left: -8%;
#media screen and (max-width: 763px) {
}
}
`;
How can I achieve my goal here?

You can stop observing the element once it's visible. Also your callbackFn doesn't have to be outside in the function body.
useEffect(() => {
const options = {
root: null,
rootMargin: "0px",
threshold: 1,
};
const callbackFn = (entries) => {
const [entry] = entries;
if(entry.isIntersecting)
{
setVisible(true);
observer.unobserve(entry.target);
}
};
const observer = new IntersectionObserver(callbackFn, options);
if (ref.current) observer.observe(ref.current);
}, [ref]);

Related

Renaming button.jsx makes entire react web unable to compile

i've been tasked with renaming a Button.jsx file for my react web app into 'v2_button.jsx' however when I do so it makes the entire web app unable to compile as there are many times where 'Button' is called but not 'v2_button'. My question is how do I make it so that I can update the name of the jsx file and update every instance where the original Button.jsx is called into 'v2_button'?
Button.jsx file:
import styled from 'styled-components';
const Button = styled.Button`
display: flex;
align-items: center;
justify-content: center;
height: 50px;
width: 300px;
background: ${(props) => {
let bg;
if (props.disabled) {
bg = props.theme.colors.disabled.background;
} else if (props.color === 'secondary') {
bg = props.theme.colors.primary.main;
} else if (props.color === 'danger') {
bg = props.theme.colors.danger.main;
} else {
bg = props.theme.colors.white;
}
return bg;
}};
font-family: ${(props) => props.theme.font.font3.new};
font-size: 18px;
font-weight: ${(props) => props.theme.fontWeight.heavy_900};
letter-spacing: 0.105em;
color: ${(props) => {
let fontColor;
if (props.color === 'secondary') {
fontColor = props.theme.colors.textPrimary.light;
} else {
fontColor = props.theme.colors.textPrimary.purple.dark;
}
return fontColor;
}};
padding: ${(props) => {
let padding;
if (props.size !== 's') {
padding = '0 39px';
}
return padding;
}};
border-radius: 40px;
border: ${(props) =>
props.disabled
? `1px solid ${props.theme.colors.disabled.border}`
: 'none'};
white-space: nowrap;
transition: background ${(props) => props.theme.animations.short} linear;
:hover {
background: ${(props) => {
let bg;
if (props.disabled) {
bg = props.theme.colors.disabled.background;
} else if (props.color === 'secondary') {
bg = props.theme.colors.primary.light;
} else if (props.color === 'danger') {
bg = props.theme.colors.danger.light;
} else {
bg = props.theme.colors.secondary.light;
}
return bg;
}};
cursor: pointer;
}
`;
export default Button;
Example where Button is called:
import styled from 'styled-components';
import Button from "../../Button";
export const Wrapper = styled.div`
display: flex;
flex-direction: column;
`;
export const Container = styled.div`
display: flex;
flex-direction: column;
`;
export const NameContainer = styled.div`
width: 100%;
display: flex;
align-content: space-between;
flex-direction: row;
font-style: normal;
font-weight: ${(props) => props.theme.fontWeight.med_500};
font-size: ${(props) => props.theme.fontSize.med_16};
`;
export const List = styled.div`
display: flex;
`;
export const FieldLabel = styled.label`
height: 36px;
color: ${(props) => props.theme.colors.white};
font-family: ${(props) => props.theme.font.font1.demi};
margin: 0 0 25px 0;
text-align: center;
font-style: normal;
font-weight: ${(props) => props.theme.fontWeight.heavy_800};
font-size: ${(props) => props.theme.fontSize.large_28};
line-height: 50px;
`;
export const Selected = styled.label`
width: 158px;
height: 40px;
margin: 0 10px 20px 10px;
padding-top: 10px;
padding-left: 20px;
font-size: ${(props) => props.theme.fontSize.med_20};
color: ${(props) => props.theme.colors.white};
font-family: ${(props) => props.theme.font.font1};
caret-color: ${(props) => props.theme.colors.textSecondary.main};
:focus {
outline: none;
}
:focus-within {
box-shadow: inset 0px 0px 2px 1px
${(props) => props.theme.colors.textSecondary.main};
}
::placeholder {
color: ${(props) => props.theme.colors.textPrimary.light};
}
background: ${(props) => props.theme.colors.primary.main};
border: ${(props) => props.theme.borders.textSecondary};
border-radius: 4px;
`;
export const AddFieldButton = styled(Button)`
margin: 30px;
font-size: ${(props) => props.theme.fontSize.med_20};
color: ${(props) => props.theme.colors.textSecondary.main};
background: none;
width: 1px;
text-align: center;
`;
Compiling error I receive after changing Button.jsx to v2_button.jsx:
https://imgur.com/a/kC0AdmG
The best thing is to renamed all the imports.
But a 'workaround' to renaming all the imports could be:
Keep the Button.jsx
Instead of exporting the default implementation, import the implementation from v2_button.jsx file and re-export it from the Button.jsx file.
Thus, every import of Button.tsx will actually refer to the implementation of v2_button.tsx file.
Example:
Button_v1.tsx
const Button_v1 = () => (
<>Button v1</>
);
export default Button_v1;
Button_v2.tsx
const Button_v2 = () => (
<>Button v2</>
);
export default Button_v2;
Since all other files reference Button_v1 and you don't want OR can't update the imports, you could do this:
Button_v1.tsx (after)
import Button_v2 from "./Button_v2"; // <-- ADDED THIS
const Button_v1 = () => (
<>Button v1</>
);
// export default Button_v1; // <-- COMMENTED THIS
export default Button_v2; // <-- ADDED THIS

Implementing animation when removing Toast

I have a working ToastList that enables me to click a button multiple times and generate a toast each time. On entry, I have an animation, but when I remove the toast, I do not get an animation. I am using Typescript and functional components.
My component is as follows:
import React, { useCallback, useEffect, useState } from 'react';
import * as Styled from './Toast.styled';
export interface ToastItem {
id: number;
title: string;
description: string;
backgroundColor: string;
}
export interface ToastProps {
toastList: ToastItem[];
setList: React.Dispatch<React.SetStateAction<ToastItem[]>>;
}
export default function Toast(props: ToastProps) {
const deleteToast = useCallback(
(id: number) => {
const toastListItem = props.toastList.filter((e) => e.id !== id);
props.setList(toastListItem);
},
[props.toastList, props.setList]
);
useEffect(() => {
const interval = setInterval(() => {
if (props.toastList.length) {
deleteToast(props.toastList[0].id);
}
}, 2000);
return () => {
clearInterval(interval);
};
}, [props.toastList, deleteToast]);
return (
<Styled.BottomRight>
{props.toastList.map((toast, i) => (
<Styled.Notification
key={i}
style={{ backgroundColor: toast.backgroundColor }}
>
<button onClick={() => deleteToast(toast.id)}>X</button>
<div>
<Styled.Title>{toast.title}</Styled.Title>
<Styled.Description>{toast.description}</Styled.Description>
</div>
</Styled.Notification>
))}
</Styled.BottomRight>
);
}
And my styling is done using styled-components and is as follows:
import styled, { keyframes } from 'styled-components';
export const Container = styled.div`
font-size: 14px;
position: fixed;
z-index: 10;
& button {
float: right;
background: none;
border: none;
color: #fff;
opacity: 0.8;
cursor: pointer;
}
`;
const toastEnter = keyframes`
from {
transform: translateX(100%);
}
to {
transform: translateX(0%);
}
}
`;
export const BottomRight = styled(Container)`
bottom: 2rem;
right: 1rem;
`;
export const Notification = styled.div`
width: 365px;
color: #fff;
padding: 15px 15px 10px 10px;
margin-bottom: 1rem;
border-radius: 4px;
box-shadow: 0 0 10px #999;
opacity: 0.9;
transition .1s ease;
animation: ${toastEnter} 0.5s;
&:hover {
box-shadow: 0 0 12px #fff;
opacity: 1;
}
`;
export const Title = styled.p`
font-weight: 700;
font-size: 16px;
text-align: left;
margin-bottom: 6px;
`;
export const Description = styled.p`
text-align: left;
`;
When I click a button, I just add an element to the state list, like:
toastProps = {
id: list.length + 1,
title: 'Success',
description: 'Sentence copied to clipboard!',
backgroundColor: '#5cb85c',
};
setList([...list, toastProps]);
My component is rendered like:
<Toast toastList={list} setList={setList}></Toast>
I would like to add animation when a toast exits, but do not know how. I have tried changing the style according to an additional prop I would send to the styled components, but this way all the toasts animate at the same time. My intuition is that I should use useRef(), but I am not sure how. Thanks in advance for any help you can provide.

flex row exceeding page width, text-overflow: ellipsis not working

my apps flex capabilities have changed since adding some code.
In my MovieContainer ideally I want the flex-direction to be row (it's currently set to column) and only the width of the page and then to start again on the next column ideally 6 across.
But when set to row it goes outside the scope of my page.
Also since adding this new code the text-overflow on my MovieName is now exceeding its width and overflow is no longer hidden.
I feel like I've effected these styled components somehow although when I change the font-size it works fine.
Styled Components:
const MovieContainer = styled.div`
display: flex;
flex-direction: column;
padding: 10px;
width: 280px;
box-shadow: 0 3px 10px 0 #aaa;
cursor: pointer;
`;
const CoverImage = styled.img`
height: 362px;
`;
const MovieName = styled.span`
font-size: 18px;
font-weight: 600;
color: black;
margin: 15px 0;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
`;
const InfoColumn = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
`;
const MovieInfo = styled.span`
font-size: 12px;
font-weight: 500;
color: black;
text-transform: capitalize;
`;
Rest of the code:
const MovieComponent = () => {
const [filmWorld, setFilmWorld] = useState([]);
const [cinemaWorld, setCinemaWorld] = useState([]);
useEffect(() => {
const theaters = ["cinema", "film"];
theaters.forEach((theater) => {
async function fetchCinema() {
const data = await api.getFilm(theater);
if (data.Provider === "Film World") {
console.log("FILM WORLD: ", data.Provider);
console.log(`Data ${theater}World: `, data);
setFilmWorld(data);
} else {
console.log("CINEMAWORLD: ", data.Provider);
console.log(`Data ${theater}World: `, data);
setCinemaWorld(data);
}
}
fetchCinema();
});
}, []);
const movies = useMemo(() => {
if (!filmWorld.Provider) return [];
return filmWorld.Movies.map((movie, index) => ({
...movie,
cinemaWorldPrice:
cinemaWorld.Provider && cinemaWorld.Movies[index]?.Price,
}));
}, [filmWorld, cinemaWorld]);
Since making changes to the below code the styling seems to go out of wack. This is where the styled components are called:
return (
<MovieContainer>
{movies.map((movie, index) => (
<div className="movies" key={index}>
<MovieName>{movie.Title}</MovieName>
<CoverImage src={movie.Poster} alt={movie.Title} />
<InfoColumn>
<MovieInfo>Filmworld Price: ${movie.Price}</MovieInfo>
<MovieInfo>Cinemaworld Price: ${movie.cinemaWorldPrice}</MovieInfo>
</InfoColumn>
</div>
))}
</MovieContainer>
);
};
export default MovieComponent;
If I understood you correctly this is what you trying to achieve:
If that is the case all you have to do is add this line:
const MovieContainer = styled.div`
.
.
.
flex-direction: row;
flex-wrap: wrap;
`;

In React, how to setState a Data by using hook useState?

I am just getting started learning React Functional component and styled- component. I tried to setState detailePageData
const const [marketPriceData, setMarketPriceData] = useState([]);
and I tried to set up the marketPriceData by using JSON file.
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history));
}, []);
When I console.log marketPriceData. I got this
In here, I only need the price in each array. So, when I console.log(marketPriceData[0].price); I got 378000 what I expected.
Here is my main question, I only need each array price such as; 378000,341000,388000, etc.
I think I have to edit this part
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history));
}, []);
First, I think "Can I use foreach method? or for loop..?" I am not sure how to setup the logic to store the setMarketPriceData. Could you please help me with how to get the price what I expected?
Just in case, I will leave the whole code,
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { FaRegArrowAltCircleDown } from 'react-icons/fa';
import { Line } from 'react-chartjs-2';
import { Modal } from './components/Modal';
import TransitionHistoryModalStyling from '../ProductDetail/components/TransitionHistoryModalStyling';
import DropDownMenu from '../ProductDetail/components/DropDownMenu';
const options = {
scales: {
y: {
beginAtZero: true,
},
},
};
export default function MarketPrice() {
const [showModal, setShowModal] = useState(false);
const [marketPriceData, setMarketPriceData] = useState([]);
// https://github.com/reactchartjs/react-chartjs-2/blob/master/example/src/charts/Line.js
const data = {
labels: ['1', '2', '3', '4', '5', '6'],
datasets: [
{
label: 'MarketPrice',
data: marketPriceData,
fill: false,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgba(255, 99, 132, 0.2)',
},
],
};
// useEffect(() => {
// let i = 1;
// if (i < detailPageData.order_history.length) {
// setMarketPriceData(detailPageData.order_history[i].price);
// }
// },[]);
const [detailPageData, setDetailPageData] = useState([]);
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setDetailPageData(data.result));
}, []);
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history));
}, []);
console.log(marketPriceData);
console.log(marketPriceData[0].price);
// console.log(detailPageData.market_price[0].sizes[0].size);
// console.log(detailPageData.order_history);
// console.log(detailPageData.order_history.length);
// console.log(detailPageData.order_history[0].price);
// console.log(detailPageData.order_history.price);
const [currentMenuIndex, setCurrentMenuIndex] = useState(1);
const handleSelectedMenu = tabIndex => {
setCurrentMenuIndex(tabIndex);
};
const openModal = () => {
setShowModal(prev => !prev);
};
return (
<MarketPriceWrapper>
<TitleWrapper>
<MarketPriceTitle>시세</MarketPriceTitle>
<ShowAllSizes>
{/* <AllSize>230</AllSize>
<FaRegArrowAltCircleDown /> */}
<DropDownMenu className={DropDownMenu} />
</ShowAllSizes>
</TitleWrapper>
<SalesGraphWrapper>
<Line data={data} options={options} />
</SalesGraphWrapper>
<ButtonsWrapper>
<Button
isActive={currentMenuIndex === 1}
onClick={() => handleSelectedMenu(1)}
>
체결 거래
</Button>
<Button
isActive={currentMenuIndex === 2}
onClick={() => handleSelectedMenu(2)}
>
판매 입찰
</Button>
<Button
isActive={currentMenuIndex === 3}
onClick={() => handleSelectedMenu(3)}
>
구매 입찰
</Button>
</ButtonsWrapper>
<TableWrapper>
<TableColumnSetting>
<SizeName>사이즈</SizeName>
<PriceName>거래가</PriceName>
<DateName>거래일</DateName>
</TableColumnSetting>
<RowSection>
{/* {detailPageData.market_price &&
detailPageData.market_price.map(price => {
return console.log(price.sizes[0]);
<Size key={price.id}>
<Size>{price.sizes[price.id].size}</Size>
<Price>{price.sizes[price.id].avg_price}</Price>
<Date>{price.date}</Date>
</Size>
})} */}
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<OrderHistoryButton onClick={openModal}>
체결 내역 더보기
</OrderHistoryButton>
<Modal showModal={showModal} setShowModal={setShowModal}>
<TransitionHistoryModalStyling
detailPageDataMarket={detailPageData}
/>
</Modal>
</TableWrapper>
</MarketPriceWrapper>
);
}
const MarketPriceWrapper = styled.div`
width: 550px;
margin-top: 40px;
padding-left: 40px;
`;
const TitleWrapper = styled.div`
display: flex;
padding-top: 19px;
padding-bottom: 12px;
border-bottom: 1px solid #ebebeb;
`;
const SalesGraphWrapper = styled.div``;
const MarketPriceTitle = styled.span`
padding-top: 4px;
display: inline-block;
line-height: 16px;
font-weight: bold;
color: #222;
`;
const ShowAllSizes = styled.div`
margin-left: 370px;
`;
const AllSize = styled.span`
display: inline-block;
margin-right: 5px;
margin-left: 350px;
font-size: 18px;
`;
const ButtonsWrapper = styled.div`
display: flex;
justify-content: space-evenly;
margin-top: 40px;
border-radius: 10px;
background-color: #f4f4f4;
`;
const Button = styled.button`
display: block;
margin: 2px;
line-height: 16px;
padding: 7px 0 9px;
width: 400px;
font-size: 13px;
text-align: center;
border-radius: 8px;
border: none;
background-color: ${props => (props.isActive ? '#ffff' : '#f4f4f4')};
color: rgba(34, 34, 34, 0.8);
`;
const TableWrapper = styled.div`
margin-top: 40px;
`;
const TableColumnSetting = styled.div`
border-bottom: 1px solid #ebebeb;
padding-bottom: 9px;
text-align: right;
`;
const SizeName = styled.span`
display: inline-block;
margin-right: 250px;
font-size: 12px;
color: rgba(34, 34, 34, 0.5);
font-weight: 400;
`;
const PriceName = styled.span`
display: inline-block;
margin-right: 150px;
font-size: 12px;
color: rgba(34, 34, 34, 0.5);
font-weight: 400;
`;
const DateName = styled.span`
display: inline-block;
font-size: 12px;
color: rgba(34, 34, 34, 0.5);
font-weight: 400;
`;
const RowSection = styled.div`
margin-top: 4px;
text-align: right;
`;
const Size = styled.span`
display: inline-block;
margin-right: 240px;
color: #222;
font-size: 12px;
`;
const Price = styled.span`
display: inline-block;
margin-right: 130px;
color: #222;
font-size: 12px;
`;
const Date = styled.span`
display: inline-block;
color: #222;
font-size: 12px;
`;
const OrderHistoryButton = styled.button`
border: 1px solid #d3d3d3;
margin-top: 40px;
background-color: #ffffff;
color: rgba(34, 34, 34, 0.8);
font-weight: 400;
padding: 0 18px;
width: 500px;
height: 42px;
border-radius: 12px;
font-size: 14px;
`;
const const [marketPriceData, setMarketPriceData] = useState([]);
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history.map(item => item.price));
}, []);
maybe you can use map in your object data result.
data.result.order_history.map((item)=>{
return item.price
}
That will only get de price property in in your array.
setMarketPriceData(data.result.order_history.map((item)=>{
return item.price
})

How to add functions inside styled-components

i pass the open a prop to the component which is a boolean
i want to add a setTimeout function to hide a component but it shows syntax error
Timeout' is not assignable to parameter of type
'Interpolation<ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>,
HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>>
here is what i tried
const DrawerContent = styled.div<{ open: boolean; visible?: any }>`
transition: 0.3s all;
${({ open, visible }) =>
open
? css`
display: flex;
width: 200px;
height: 100px;
background-color: brown;
position: absolute;
top: 0;
`
: setTimeout(() => { // i want to add this line
css`
display: none;
`;
}, 200)}
`;
You can't get a return value from the setTimeout callback function. If you are trying to hide the node after some time, you should use keyframes:
const hide = keyframes`
to {
width:0;
height:0;
overflow:hidden;
}
`;
const DrawerContent = styled.div`
transition: 0.3s all;
${({ open, visible }) =>
open &&
css`
display: flex;
width: 200px;
height: 100px;
background-color: brown;
position: absolute;
top: 0;
animation: ${hide} 0s ease-in 2s forwards;
`}
`;
Another solution is to move the timeout function outside the DrawerContent component:
const DrawerContent = styled.div`
transition: 0.3s all;
${({ open, visible }) =>
open &&
css`
display: flex;
width: 200px;
height: 100px;
background-color: brown;
position: absolute;
top: 0;
`}
`;
function App () {
const [show, setShow] = useState(true);
useEffect(() => {
let timeout;
if (show) {
timeout = setTimeout(() => {
setShow(false);
}, 2000);
}
return () => clearTimeout(timeout);
}, [show]);
return (
<>
<div>
<DrawerContent open={show} visible />
</div>
</>
);
}

Resources