OK guys, so I'm noob in React, and I know that I'm mistaken something, but I can't see what.
I put loading spinners between my pages and no problems, until this page :
So I have this page that is scrolling on X axe and a logo spinning during scroll, until know, all was working correctly. And there is the code without the loading spinner :
import React, { useEffect, useRef } from "react";
import styled, { ThemeProvider } from "styled-components";
import { DarkTheme } from "./Themes";
import {motion} from 'framer-motion';
import LogoComponent from '../subComponents/LogoComponent';
import SocialIcons from '../subComponents/SocialIcons';
import PowerButton from '../subComponents/PowerButton';
import { Work } from '../data/WorkData';
import Card from "../subComponents/Card";
import { Umbrella } from "./AllSvgs";
import BigTitle from "../subComponents/BigTitle";
const Box = styled.div`
background-color: ${props => props.theme.body};
height: 400vh;
position: relative;
display: flex;
align-items: center;
`
const Main = styled(motion.ul)`
position: fixed;
top: 12rem;
left: calc(10rem + 15vw);
height: 40vh;
display: flex;
color: white;
`
const Rotate = styled.span`
display: block;
position: fixed;
right: 1rem;
bottom: 1rem;
width: 80px;
height: 80px;
z-index:1;
`
// Framer-motion configuration
const container = {
hidden: {opacity:0},
show: {
opacity:1,
transition: {
staggerChildren:0.5,
duration:0.5,
}
}
}
const WorkPage = () => {
const ref = useRef(null);
const umbrella = useRef(null);
useEffect(() => {
let element = ref.current;
const rotate = () => {
element.style.transform = `translateX(${-window.scrollY}px)`
umbrella.current.style.transform = `rotate(` + -window.scrollY + 'deg)'
}
window.addEventListener('scroll', rotate)
return () => window.removeEventListener('scroll', rotate)
}, [])
return (
<ThemeProvider theme={DarkTheme}>
<Box>
<LogoComponent theme='dark'/>
<SocialIcons theme='dark'/>
<PowerButton />
<Main ref={ref} variants={container} initial='hidden' animate='show' >
{
Work.map( d =>
<Card key={d.id} data={d} />
)
}
</Main>
<Rotate ref={umbrella}>
<Umbrella width={80} height={80} fill={DarkTheme.theme} />
</Rotate>
<BigTitle text="PROJETS" top="10%" right="20%" />
</Box>
</ThemeProvider>
)
}
export default WorkPage
Then I put the code with the same logic than the other pages that are working :
import React, { useEffect, useRef, useState } from "react";
import styled, { ThemeProvider } from "styled-components";
import { DarkTheme } from "./Themes";
import {motion} from 'framer-motion';
import RingLoader from "react-spinners/RingLoader";
import { css } from "#emotion/react";
import LogoComponent from '../subComponents/LogoComponent';
import SocialIcons from '../subComponents/SocialIcons';
import PowerButton from '../subComponents/PowerButton';
import { Work } from '../data/WorkData';
import Card from "../subComponents/Card";
import { Umbrella } from "./AllSvgs";
import BigTitle from "../subComponents/BigTitle";
const Box = styled.div`
background-color: ${props => props.theme.body};
height: 400vh;
position: relative;
display: flex;
align-items: center;
`
const Main = styled(motion.ul)`
position: fixed;
top: 12rem;
left: calc(10rem + 15vw);
height: 40vh;
display: flex;
color: white;
`
const Rotate = styled.span`
display: block;
position: fixed;
right: 1rem;
bottom: 1rem;
width: 80px;
height: 80px;
z-index:1;
`
const override = css`
position: absolute;
bottom: 10%;
right: 10%;
`
// Framer-motion configuration
const container = {
hidden: {opacity:0},
show: {
opacity:1,
transition: {
staggerChildren:0.5,
duration:0.5,
}
}
}
const WorkPage = () => {
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true)
setTimeout(() => {
setLoading(false)
}, 2000)
}, [])
const ref = useRef(null);
const umbrella = useRef(null);
useEffect(() => {
let element = ref.current;
const rotate = () => {
element.style.transform = `translateX(${-window.scrollY}px)`
umbrella.current.style.transform = `rotate(` + -window.scrollY + 'deg)'
}
window.addEventListener('scroll', rotate)
return () => window.removeEventListener('scroll', rotate)
}, [])
return (
<ThemeProvider theme={DarkTheme}>
{
loading ?
<RingLoader
color={'#000'}
loading={loading}
size={60}
css={override}
/>
:
<Box>
<LogoComponent theme='dark'/>
<SocialIcons theme='dark'/>
<PowerButton />
<Main ref={ref} variants={container} initial='hidden' animate='show' >
{
Work.map( d =>
<Card key={d.id} data={d} />
)
}
</Main>
<Rotate ref={umbrella}>
<Umbrella width={80} height={80} fill={DarkTheme.theme} />
</Rotate>
<BigTitle text="PROJETS" top="10%" right="20%" />
</Box>
}
</ThemeProvider>
)
}
export default WorkPage
And the scroll is not working anymore. The logo is still spinning. I try to put in conditions, but nope.
Put the useState on true, but then I have an error on the rotate func :
TypeError: Cannot read properties of null (reading 'style')
rotate
src/components/WorkPage.js:89
86 | let element = ref.current;
87 |
88 | const rotate = () => {
> 89 | element.style.transform = `translateX(${-window.scrollY}px)`
| ^ 90 |
91 | umbrella.current.style.transform = `rotate(` + -window.scrollY + 'deg)'
92 | }
I don't see what I'm missing... Thanks y'all 🙏
In your second example code (where you added loading and setLoading from the useState hook), the <Box> component (which contains the <Main ref={ref}... component) doesn't get rendered when loading is set to true (and you're setting it to true in your first useEffect).
Since the <Main ref={ref}... component isn't being rendered, the line let element = ref.current will initialize element as null. (that's why you're getting that error)
Related
I'm trying to make a toast message component that works like this.
It comes in from outside the right screen, disappears out of the screen after a certain period of time, and the component get deleted after the animation.
It works perfectly when I make a single component. However, when I create multiple toast components, some of them just get removed before the animation starts.
I tried many ways for 3days, but nothing worked... 😭 I would appreciate it if you could check which part is wrong. Help me plz
Toast Contatiner
import React, { useState, useCallback } from 'react';
import ToastItem from './Toast';
import styled from 'styled-components';
type ToastItemInfo = {
content: string | React.ReactNode;
id: string;
};
const ToastContainer = () => {
const [toastItems, setToastItems] = useState<ToastItemInfo[]>([]);
const handleClick = () => {
setToastItems((toastItems) => [
{
content: 'Toasted !',
id: String(Math.random()).substring(2, 8),
},
...toastItems,
]);
};
const removeToast = useCallback((id: string) => {
setToastItems((toastItems) => toastItems.filter((toast) => toast.id !== id));
}, []);
const hasItems = (toastItems: ToastItemInfo[]) => {
return toastItems.length > 0;
};
const mapItems = (toastItems: ToastItemInfo[]) => {
return toastItems.map((toast) => (
<ToastItem key={toast.id} id={toast.id} removeToast={removeToast}>
{toast.content}
</ToastItem>
));
};
return (
<div>
<Button onClick={handleClick}>Toast 🍞</Button>
{hasItems(toastItems) && <Container>{mapItems(toastItems)}</Container>}
</div>
);
};
const Container = styled.div`
position: fixed;
display: flex;
flex-direction: column;
gap: 8px;
top: 0;
right: 0;
margin: 16px;
`;
// .slideout {
// animation: 0.5s linear animate;
// }
// #keyframes animate {
// from {
// transform: translateX(0);
// }
// to {
// transform: translateX(120%);
// }
// }
const Button = styled.button`
width: 132px;
height: 40px;
background: #434253;
color: white;
font-size: 1rem;
border: 2px solid white;
cursor: pointer;
`;
export default ToastContainer;
ToastItem
import React, { memo, useEffect, useRef, useState } from 'react';
import styled, { keyframes } from 'styled-components';
import ProgressBar from './ProgressBar';
interface ToastProps {
id: string;
children: string | React.ReactNode;
removeToast: (id: string) => void;
}
const autoCloseDelay = 3000;
const ToastItem: React.FC<ToastProps> = (props) => {
const { id, removeToast, children } = props;
const [toClose, setToClose] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const removeFn = () => {
removeToast(id);
};
const { current } = ref;
const timeout = setTimeout(() => {
current?.addEventListener('animationend', () => {
removeToast(id);
});
setToClose(true);
}, autoCloseDelay);
return () => {
clearTimeout(timeout);
current?.removeEventListener('animationend', removeFn);
};
}, [id, removeToast]);
return (
<Toast id={id} ref={ref} onClick={() => removeToast(id)} toClose={toClose}>
{children}
<ProgressBar autoCloseDelay={autoCloseDelay} />
</Toast>
);
};
const slideIn = keyframes`
from{
transform: translateX(120%);
}
to{
transform: translateX(0);
}
`;
const slideOut = keyframes`
from{
transform: translateX(0);
}
to{
transform: translateX(120%);
}
`;
const Toast = styled.div<{ toClose: boolean }>`
box-sizing: border-box;
position: relative;
padding: 0 16px;
width: 250px;
height: 58px;
line-height: 58px;
background: #fabb4d;
color: #5f2700;
border-radius: 2px;
cursor: pointer;
animation: 0.5s ease 0s ${(props) => (props.toClose ? slideOut : slideIn)};
&:hover {
transform: scale(1.05);
}
`;
export default memo(ToastItem);
enter image description here
I am trying to achieve this: https://codesandbox.io/s/framer-motion-2-drag-to-reorder-fc4rt?file=/src/use-position-reorder.js
Basically you can drag a card, place it somewhere in the container and reorder the card based on where you drag/put it from the original place.
The problem is that in my code, you can drag the card but not place it. I tried to change the code so many times but I can't find a way out of it. Below you will find the code where I render the component FavouriteTreeNodeComponent which is a LI(List) nested in FavouriteTreeNodesList a UL(Unordered List) :
// react
import { useRef, useEffect, useCallback, useState } from 'react';
// animation spring
import { animated, Transition, useSpring } from 'react-spring';
import { AnimateSharedLayout } from 'framer-motion';
// styled components
import styled from 'styled-components';
// framer motion
import { motion } from 'framer-motion';
import { usePositionReorder } from './ReorderingModalNodes/use-position-reorder';
// icons
import { MdClose } from 'react-icons/md';
// components
import TemplateItem from './TemplateItem';
import SearchBar from './SearchBar';
import DurationIntervalComponent from './DurationIntervalComponent';
import ContextItem from './ContextItem';
import FavouriteTreeNodeComponent from './FavouriteTreeNodeComponent';
const TimeEntryModal = ({ showModal, setShowModal }) => {
// STATES
const [selected, setSelected] = useState('');
const [reportingTemplates, setReportingTemplates] = useState([]);
const [reportingContexts, setReportingContexts] = useState([]);
// USEREF
const modalRef = useRef();
// ANIMATION MODAL
const animation = useSpring({
config: {
duration: 250,
},
opacity: showModal ? 1 : 0,
transform: showModal ? `translateY(0%)` : `translateY(-100%)`,
});
// CLOSING MODAL FROM BACKGROUND
const closeModal = (e) => {
if (modalRef.current === e.target) {
setShowModal(false);
}
};
// CLOSING MODAL WITH ESCAPE BUTTON
const keyPress = useCallback(
(e) => {
if (e.key === 'Escape' && showModal) {
setShowModal(false);
console.log('I pressed');
}
},
[setShowModal, showModal]
);
useEffect(() => {
document.addEventListener('keydown', keyPress);
return () => document.removeEventListener('keydown', keyPress);
}, [keyPress]);
const variants = {
hidden: {
y: '-100vh',
},
visible: { y: 0, transition: { ease: 'easeInOut', duration: 1 } },
exit: {
y: '-100vh',
},
};
// DATA
const colorsData = [
'#86d8bda1',
'#eb472a83',
'#8fcfe3ad',
'#db8ddfb0',
'#e8e46fc0',
'#e1aa66b2',
];
const List = [
'3000',
'4000',
'5000',
'6000',
'7000',
'8000',
];
// FAVOURITES LIST ANIMATION
const [updatedList, updatePosition, updateOrder] =
usePositionReorder(List);
// FETCHES
useEffect(() => {
getTemplates();
}, []);
const url = 'http://localhost:8080/graphql';
const getTemplates = async () => {
try {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `query {
reportingTemplates {
name
_id
colorScheme
reportingContexts {
name
_id
}
}
}`,
}),
});
const data = await res.json();
console.log(data);
const dataWithColors = data.data.reportingTemplates.map((obj, i) => ({
...obj,
color: colorsData[i],
}));
setReportingTemplates(dataWithColors);
setSelected(dataWithColors[0].color);
setReportingContexts(dataWithColors[0].reportingContexts);
console.log('data', dataWithColors);
} catch (err) {
console.log('ERROR', err);
}
};
console.log('data state', reportingTemplates);
return (
<Background ref={modalRef} onClick={closeModal}>
<motion.div
variants={variants}
initial="hidden"
animate="visible"
exit="exit"
>
<ModalWrapper>
<ModalContent>
<Nav>
<h3>New Entry Tirsdag 2. Sep </h3>
</Nav>
<ModalColumns>
<ColumnOne>
<TemplatesContainer>
<AnimateSharedLayout>
<Templates>
{reportingTemplates.map((template, index) => (
<TemplateItem
key={template.name}
color={template.color}
title={template.name}
isSelected={selected === template.color}
onClick={() => {
setReportingContexts(
reportingTemplates[index].reportingContexts
);
setSelected(template.color);
}}
/>
))}
</Templates>
</AnimateSharedLayout>
</TemplatesContainer>
<InformationBlock>
<h4>Information</h4>
{reportingContexts.map((context) => (
<ContextItem
key={context.name}
text={context.name}
// isSelected={selected === context.color}
// onClick={() => setSelected(context.color)}
/>
))}
</InformationBlock>
<DurationIntervalComponent />
</ColumnOne>
<ColumnTwo>
<SearchBar />
<Recent>
<h4>Recent</h4>
</Recent>
<Favourites>
<h4>Favourites</h4>
<FavouriteTreeNodesList>
{updatedList.map((treeNode, index) => (
<FavouriteTreeNodeComponent
key={index}
index={index}
text={treeNode}
updateOrder={updateOrder}
updatePosition={updatePosition}
/>
))}
</FavouriteTreeNodesList>
</Favourites>
</ColumnTwo>
</ModalColumns>
</ModalContent>
<CloseModalButton
aria-label="Close Modal"
onClick={() => setShowModal((prev) => !prev)}
/>
<Footer>
<DeleteBlock>
<p> Delete </p>
</DeleteBlock>
<CancelNSaveBlock>
<Cancel>
<p> Cancel </p>
</Cancel>
<SaveNClose>
<p> Save and close </p>
</SaveNClose>
<SaveNAdd>
<p> Save and add another </p>
</SaveNAdd>
</CancelNSaveBlock>
</Footer>
</ModalWrapper>
</motion.div>
</Background>
);
};
// STYLES
const Background = styled.div`
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.5);
position: fixed;
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
`;
const ModalWrapper = styled.div`
width: 80vw;
height: 80vh;
box-shadow: 0 5px 16px rgba(0, 0, 0, 0.2);
background: #fff;
color: #000;
display: flex;
flex-direction: column;
align-items: stretch;
border-radius: 10px;
`;
const CloseModalButton = styled(MdClose)`
cursor: pointer;
position: absolute;
top: 20px;
right: 20px;
width: 32px;
height: 32px;
padding: 0;
z-index: 10;
`;
// MODAL CONTENT
const ModalContent = styled.div`
padding: 20px;
position: relative;
`;
// NAV
const Nav = styled.div``;
const ModalColumns = styled.div`
padding: 10px 0px;
display: flex;
`;
// COLUMN ONE
const ColumnOne = styled.div`
width: 50%;
padding: 20px;
`;
const TemplatesContainer = styled.div``;
const Templates = styled.ul`
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: row;
flex-wrap: initial;
justify-content: center;
`;
const InformationBlock = styled.div`
padding-bottom: 20px;
`;
// COLUMN TWO
const ColumnTwo = styled.div`
width: 50%;
padding: 20px;
`;
const Recent = styled.div`
background-color: #f6f6f9;
border: 1px solid #c5c5c5;
border-radius: 20px;
`;
const Favourites = styled.div`
list-style: none;
`;
const FavouriteTreeNodesList = styled.ul`
position: relative;
width: 100%;
`;
// FOOTER
const Footer = styled.div`
display: flex;
position: fixed;
padding: 0 20px;
bottom: 10px;
/* text-align: center; */
width: 100%;
`;
const DeleteBlock = styled.div`
color: #fb423a;
`;
const CancelNSaveBlock = styled.div`
display: flex;
margin-left: auto;
`;
// const [{name:"cancel", color func: ()=>sdasd }, "sada", "asdasd"]
const Cancel = styled.div`
color: #02b396;
margin-right: 40px;
`;
const SaveNClose = styled.div`
font-weight: bolder;
color: #02b396;
margin-right: 40px;
`;
const SaveNAdd = styled.div`
font-weight: bolder;
color: #02b396;
`;
export default TimeEntryModal;
After that the list FavouriteTreeNodeComponent is rendered in the code below:
import { useState } from 'react';
// styled components
import styled from 'styled-components';
// framer motion
import { motion } from 'framer-motion';
import { useMeasurePosition } from './ReorderingModalNodes/use-measure-position';
const FavouriteTreeNodeComponent = ({
text,
updateOrder,
updatePosition,
index,
}) => {
const [isdragged, setIsDragged] = useState(false);
const itemRef = useMeasurePosition((pos) => updatePosition(index, pos));
return (
<ListContainer>
<motion.div
style={{
zIndex: isdragged ? 2 : 1,
height: text.length * 10,
padding: "5px",
}}
dragConstraints={{
top: 0,
bottom: 0,
}}
dragElastic={1}
layout
ref={itemRef}
onDragStart={() => setIsDragged(true)}
onDragEnd={() => setIsDragged(false)}
animate={{
scale: isdragged ? 1.05 : 1,
}}
onViewportBoxUpdate={(_, delta) => {
isdragged && updateOrder(index, delta.y.translate);
}}
drag="y">{text}
</motion.div>
</ListContainer>
);
};
// STYLES
const ListContainer = styled.li`
height: auto;
gap: 9px 0px;
position: relative;
padding: 10px 0px;
list-style: none;
div {
background-color: white;
border-radius: 5px;
border: 1px solid #c5c5c5;
}
`;
export default FavouriteTreeNodeComponent;
The above code is connected to the file: useMeasurePosition same as the original project:
import { useEffect, useRef } from 'react';
export function useMeasurePosition(update) {
// We'll use a `ref` to access the DOM element that the `motion.li` produces.
// This will allow us to measure its height and position, which will be useful to
// decide when a dragging element should switch places with its siblings.
const ref = useRef(null);
// Update the measured position of the item so we can calculate when we should rearrange.
useEffect(() => {
update({
height: ref.current.offsetHeight,
top: ref.current.offsetTop,
});
});
return ref;
}
and to the file: usePositionReorder:
import { useState, useRef } from 'react';
import { clamp, distance } from 'popmotion';
import { arrayMoveImmutable as move} from 'array-move';
export function usePositionReorder(initialState) {
const [order, setOrder] = useState(initialState);
// We need to collect an array of height and position data for all of this component's
// `Item` children, so we can later us that in calculations to decide when a dragging
// `Item` should swap places with its siblings.
const positions = useRef([]).current;
const updatePosition = (i, offset) => (positions[i] = offset);
// Find the ideal index for a dragging item based on its position in the array, and its
// current drag offset. If it's different to its current index, we swap this item with that
// sibling.
const updateOrder = (i, dragOffset) => {
const targetIndex = findIndex(i, dragOffset, positions);
if (targetIndex !== i) setOrder(move(order, i, targetIndex));
};
return [order, updatePosition, updateOrder];
}
const buffer = 30;
export const findIndex = (i, yOffset, positions) => {
let target = i;
const { top, height } = positions[i];
const bottom = top + height;
// If moving down
if (yOffset > 0) {
const nextItem = positions[i + 1];
if (nextItem === undefined) return i;
const swapOffset =
distance(bottom, nextItem.top + nextItem.height / 2) + buffer;
if (yOffset > swapOffset) target = i + 1;
// If moving up
} else if (yOffset < 0) {
const prevItem = positions[i - 1];
if (prevItem === undefined) return i;
const prevBottom = prevItem.top + prevItem.height;
const swapOffset = distance(top, prevBottom - prevItem.height / 2) + buffer;
if (yOffset < -swapOffset) target = i - 1;
}
return clamp(0, positions.length, target);
};
I try to switch from an image to another one when scrolling with React but I don't know how to do this... maybe with React hook. I know it's possible with jQuery but I don't want to use it.
Example here: https://www.apple.com/iphone-12/, look at the "Five fresh finishes".
import React, {useState} from 'react';
import './BackgroundDiscover.css';
import logoOrdiW from "../../images/mathis_computer_white.jpg";
import logoOrdiB from "../../images/mathis_computer_black.jpg";
const BackgroundDiscover = () => {
const [imageSrc, SetSrc] = useState(logoOrdiW);
const switchBrackground = () => {
SetSrc(logoOrdiB);
}
return (
<>
<div className="container-discover">
<div className='container-logo-white'>
<img src={imageSrc} alt="logo ordinateur mathis blanc" onScroll={switchBrackground}/>
</div>
</div>
</>
);
};
export default BackgroundDiscover;
.container-discover {
display: flex;
flex-direction: column;
}
.container-logo-white img {
width: 100%;
}
.container-logo-black img {
width: 100%;
}
You don't need jQuery or something like this. You could subscribe to scroll event in useEffect() hook with addEventListener and check scrollTop of a scrolling container.
If you want to do the same effect as the Apple website has, you could add some magic with position: sticky, height in vh units and checking window.innerHeight.
Note that this code is simplified, not optimized, and only needed to understand the idea:
CodeSandbox
index.js:
import { useLayoutEffect, useState } from "react";
import { render } from "react-dom";
import classnames from "classnames";
import "./index.css";
const images = [0, 1, 2, 3, 4];
const App = () => {
const [visibleImagesMap, setVisibleImagesMap] = useState(
images.reduce((map, image) => {
map[image] = false;
return map;
}, {})
);
useLayoutEffect(() => {
const handleScroll = () => {
const scrollTop = document.documentElement.scrollTop;
const viewportHeight = window.innerHeight;
const newVisibleImagesMap = images.reduce((map, image) => {
map[image] = scrollTop >= image * viewportHeight;
return map;
}, {});
setVisibleImagesMap(newVisibleImagesMap);
};
window.addEventListener("scroll", handleScroll);
handleScroll();
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return (
<div className="app">
<div className="sticky">
<div className="frame">
{images.map((image) => (
<div
className={classnames("image", `image_${image}`, {
image_visible: visibleImagesMap[image]
})}
key={image}
/>
))}
</div>
</div>
</div>
);
};
render(<App />, document.getElementById("root"));
index.css:
body {
margin: 0;
}
.app {
height: 500vh;
}
.sticky {
position: sticky;
top: 0;
height: 100vh;
}
.frame {
z-index: 1;
position: relative;
height: 100%;
width: 100%;
}
.image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
background-repeat: no-repeat;
background-size: cover;
}
.image_0 {
z-index: 0;
background-image: url("./images/0.jpeg");
}
.image_1 {
z-index: 1;
background-image: url("./images/1.jpeg");
}
.image_2 {
z-index: 2;
background-image: url("./images/2.jpeg");
}
.image_3 {
z-index: 3;
background-image: url("./images/3.jpeg");
}
.image_4 {
z-index: 4;
background-image: url("./images/4.jpeg");
}
.image_visible {
opacity: 1;
}
There are plenty of solutions for this but basically you can set in this way.
Wheel event listener turns either positive or negative value so you should create an algorithm if you want to impelement different designs.
import React, { useState } from "react";
export default function App() {
const [bgImage, handleImage] = useState(
"https://media.wired.com/photos/5e9f56f143e5800008514457/1:1/w_1277,h_1277,c_limit/Gear-Feature-Apple_new-iphone-se-white_04152020.jpg"
);
window.addEventListener("wheel", (e) => {
if (e.deltaY > 0) {
handleImage(
"https://media.wired.com/photos/5bcea2642eea7906bba84c67/master/w_2560%2Cc_limit/iphonexr.jpg"
);
} else {
handleImage(
"https://media.wired.com/photos/5e9f56f143e5800008514457/1:1/w_1277,h_1277,c_limit/Gear-Feature-Apple_new-iphone-se-white_04152020.jpg"
);
}
});
return (
<div className="App">
<img
style={{ width: "400px", height: "300px" }}
id="myimage"
src={bgImage}
alt=""
/>
</div>
);
}
And as a result you can use bgImage state in your image src.
This is a codesandbox example https://codesandbox.io/s/pensive-vaughan-cfc63?fontsize=14&hidenavigation=1&theme=dark
You can try useEffect and useRef.
useEffect is sideload functions, and useRef is for real dom referances.
import React, { useRef, useState, useEffect } from 'react';
import logoOrdiW from "../../images/mathis_computer_white.jpg";
import logoOrdiB from "../../images/mathis_computer_black.jpg";
import './BackgroundDiscover.css';
const BackgroundDiscover = () => {
const img = useRef();
const [src, setSrc] = useState(logoOrdiW);
const switchBrackground = () => {
setSrc(logoOrdiB);
}
useEffect(() => {
img.current.onscroll = switchBrackground;
}, []);
return (
<div className="container-discover">
<div className='container-logo-white'>
<img src={src} alt="logo ordinateur mathis blanc" ref={img} />
</div>
</div>
);
};
export default BackgroundDiscover;
I am trying to write a react component where I can load different styled div-s according to passed props and render them. This is my code so far:
Component:
import React, { Component } from "react";
import s, { keyframes } from "styled-components";
import PropTypes from "prop-types";
import { jumpyRotation } from "../animations/jumpyRotation.js";
import { normalRotation } from "../animations/normalRotation.js";
import { baseShape } from "../shapes/base";
const animations = {
jumpyRotation: jumpyRotation,
normalRotation: normalRotation
};
const shapes = {
square: baseShape
};
class Loader extends Component {
render() {
const {
size = "14px",
color = "#000",
fontSize = "14px",
loaderText = "Loading...",
length = "4s",
animation = "jumpyRotation",
shape = "square"
} = this.props;
const styledShape = shapes[shape];
styledShape.attrs.size = size;
styledShape.attrs.color = color;
styledShape.attrs.animation = animation;
styledShape.attrs.length = length;
return (
<LoaderStyles
length={length}
animation={animations[animation]}
fontSize={fontSize}
color={color}
size={size}
>
styledShape
<span className="loader-text">{loaderText}</span>
</LoaderStyles>
);
}
}
Loader.propTypes = {
size: PropTypes.string, // Size in a valid CSS unit
color: PropTypes.string, // A valid CSS color, changes both loader and text
fontSize: PropTypes.string, // Size in a valid CSS unit
loaderText: PropTypes.string, // Text displayed under the loader
length: PropTypes.string, // The length of animation in a valid CSS unit
animation: PropTypes.string // The name of the animation
};
const LoaderStyles = s.div`
font-size: ${props => props.fontSize};
display: flex;
align-items: center;
justify-items: center;
flex-direction: column;
padding: ${props => props.fontSize};
.loader-text {
color: ${props => props.color};
}
`;
export default Loader;
Styled component ../shapes/base:
import s from "styled-components";
export const baseShape = s.div`
margin: ${props => props.size};
height: ${props => props.size};
width: ${props => props.size};
background-color: ${props => props.color};
animation: ${props => props.animation} ${props =>
props.length} linear infinite;
`;
Now according to the styled component docs, using the syntax should work, but I get the following error:
TypeError: Cannot set property 'size' of undefined
Even though the browser debugger shows styledShape as a styled.div
React only recognizes components if they start with capital letters, so the solution was this (omitted irrelevant code from the anwser):
Styled component:
import s from "styled-components";
export const baseShape = s.div`
margin: ${Brops => props.size};
height: ${props => props.size};
width: ${props => props.size};
background-color: ${props => props.color};
animation: ${props => props.animation} ${props =>
props.length} linear infinite;
`;
Component:
import React, { Component } from "react";
import s from "styled-components";
import { BaseShape } from "../shapes/base";
const shapes = {
square: BaseShape
};
class Loader extends Component {
render() {
const {
size,
color,
animation,
shape
} = this.props;
const ShapeDiv = shapes[shape];
return (
<ShapeDiv size={size} color={color} animation={animation} shape={shape}/>
);
}
}
export default Loader;
I'm trying to implement a loader to my react component, when the background image is loading it should display 'loading' and then once it has loaded it should display 'loaded'
I have a setTimeout() on my componentwillMount() to test that the loader functions as expected which it does
I'm struggling to understand how it knows when the image is loaded and to change the loading state
Is it best to put the image into a seperate component with the loader rather than have it on the Hello component?
https://www.webpackbin.com/bins/-KsOEkf9ubvR6iz4bMxG
Update
I have managed to get a simple image loader working using the onload() method attached to the image - https://www.webpackbin.com/bins/-KsNpZPzveUoby1yriFo
Hello.js
import React from 'react'
import Loader from './Loader'
import styled from 'styled-components'
const Card = styled.div`
height: 400px;
width:20%;
background: url('https://www.planwallpaper.com/static/images/Light-Wood-Background-Wallpaper.jpg');
`
export default class Test extends React.Component {
constructor() {
super()
this.state = { loading:true}
}
componentWillMount()
{
setTimeout(() => this.setState({loading: false}), 3000)
console.log("componentDidMount");
}
render() {
return (
<div>
<Card>
<Loader loading={this.state.loading} />
</Card>
</div>
)
}
}
Loader.js
import React, { Component } from 'react'
import styled, { keyframes } from 'styled-components'
import { string } from 'prop-types'
const transition1 = keyframes`
0% { background: #F19939; }
33.33% { background: #F8CA8F; }
66.66% { background: #FBD8AE; }
100% { background: #F19939; }
`
const transition2 = keyframes`
0% { background: #FBD8AE; }
33.33% { background: #F19939; }
66.66% { background: #F8CA8F; }
100% { background: #FBD8AE; }
`
const transition3 = keyframes`
0% { background: #F8CA8F; }
33.33% { background: #FBD8AE; }
66.66% { background: #F19939; }
100% { background: #F8CA8F; }
`
const Box = styled.span`
height: 12px;
width: 12px;
margin: 0 3px 0 3px;
border-radius: 4px;
animation: 0.4s ${transition1 } infinite;
`
const Box2 = styled(Box)`
animation: 0.4s ${transition2 } infinite;
`
const Box3 = styled(Box)`
animation: 0.4s ${transition3 } infinite;
`
const TextWrap = styled.div`
display: flex;
flex: 0 0 100%;
justify-content: center;
color: #fff;
`
const Para = styled.p`
color: #fff
padding: 19px 0 0 0;
`
const ParaLoaded = styled(Para)`
color: #fff;
padding: 22px 0 0 0;
`
export default class Loader extends Component {
render() {
return (
<div >
<div >
<TextWrap>
{
this.props.loading
?
<Para>Loading...</Para>
:
<ParaLoaded>Loaded</ParaLoaded>
}
</TextWrap>
</div>
</div>
)
}
}
You can do it like this: https://www.webpackbin.com/bins/-KsOJpBVfpazfXghJAaF
LoadBackgroundImage.js
const LoadBackgroundImage = (component, imageUrl, seconds, success, failure) => {
let timeoutOccured = false;
const image = new Image();
const timeout = setTimeout(() => {
timeoutOccured = true;
failure();
}, seconds * 1000);
image.onload = () => {
clearTimeout(timeout);
component.style.backgroundImage = `url('${imageUrl}')`;
if (!timeoutOccured) success();
};
image.src = imageUrl;
};
export default LoadBackgroundImage;
Hello.js
import React from 'react'
import Loader from './Loader'
import styled from 'styled-components'
import LoadBackgroundImage from './LoadBackgroundImage'
const Card = styled.div`
height: 400px;
width:20%;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = { loading:true}
}
componentDidMount() {
LoadBackgroundImage(
this.card,
'https://www.planwallpaper.com/static/images/Light-Wood-Background-Wallpaper.jpg',
5,
() => this.setState({ loading: false }),
() => console.log('The image did not load in 5 seconds')
);
}
render() {
return (
<div>
<Card innerRef={card => this.card = card}>
<Loader loading={this.state.loading} />
</Card>
</div>
)
}
}
In render() you are using innerRef to obtain a reference to the card component and save it in this.card. Then in componentDidMount you are using this reference and LoadBackgroundImage function to load the image and monitor when it's loaded. If the image is loaded in given number of second success callback will be called, otherwise failure callback will be called. The image can still load after 5 seconds, but the success callback will not be called. If you want to be called anyway, you can skip this ckeck: if (!timeoutOccured) in LoadBackgroundImage function.