I am attempting to reproduce the sliding image effect seen on this website https://chiwawa.es/en/.
I can see how it works on this website (see changeImages function in 63c2acc.js; however, getting this to work in React is proving difficult for me.
To illustrate what I have managed to do, I've published https://dskdirhhwk.vercel.app/.
Solved - (this link now correctly shows animations thanks to answer below)
The difficulty I'm running into is animating the images. The Sections are getting re-rendered by React upon state update, affecting how I apply the classes to the markup. I used Reacts Profiler to verify these are updates, not remounts.
I initially had the Intersection Observer outside the Section component, but this didn't appear to work. I also had a simple setState mechanism and have since built it into a reducer, so that I could add the active class after the other classes.
I am pulling my hair out here. I want a few hints and a push in the right direction!
This is on Next.js. Here is my code.
import React, {
Fragment,
useState,
forwardRef,
useEffect,
useLayoutEffect,
useCallback,
useContext,
useRef,
useMemo,
} from 'react';
import cx from 'classnames';
// yarn add classnames
const useIntersect = ({root = null, rootMargin, threshold = 0}) => {
const [entry, updateEntry] = useState({});
const [node, setNode] = useState(null);
const observer = useRef(null);
useEffect(() => {
if (observer.current) observer.current.disconnect();
observer.current = new IntersectionObserver(([entry]) => updateEntry(entry), {
root,
rootMargin,
threshold,
});
const {current: currentObserver} = observer;
if (node) currentObserver.observe(node);
return () => currentObserver.disconnect();
}, [node]);
return [setNode, entry];
};
const Home = () => {
const initialState = {active: 'teal', current: 'teal'};
const [state, dispatch] = React.useReducer(reducer, initialState);
function reducer(state, {section, type}) {
switch (type) {
case 'reset':
return initialState;
case 'changeSection':
return {
...state,
previous: state?.current,
current: section,
};
case 'makeActive':
return {
...state,
active: section,
};
default:
return state;
}
}
const activeSection = (section) => {
dispatch({section: section, type: 'changeSection'});
setTimeout(() => {
dispatch({type: 'makeActive', section: section});
}, 1000);
};
const Section = ({sectionID, className, children}) => {
const [ref, entry] = useIntersect({
threshold: '0.7',
});
useEffect(() => {
if (state?.current == sectionID) return;
if (entry.isIntersecting) {
activeSection(sectionID);
}
}, [entry]);
const childrenWithProps = React.Children.map(children, (child, index) => {
if (React.isValidElement(child)) {
if (index == 0)
return React.cloneElement(child, {
className: cx(
'fixed top-0 w-1/2 h-screen transition-all duration-[1000ms] place-items-center place-content-center transform-gpu',
{
'translate-y-[-100vh]': sectionID != state?.active,
'z-40 translate-y-0': sectionID == state?.current && sectionID == state?.active,
}
),
data: 'observable',
id: sectionID,
});
}
return child;
});
return (
<section className={className} ref={ref}>
{childrenWithProps}
</section>
);
};
return (
<>
<div className="fixed bottom-0 z-50 w-1/2 opacity-50">
<pre>{JSON.stringify(state, null, 2)}</pre>
</div>
<Section sectionID="teal" className="bg-teal-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=1" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
<Section sectionID="blue" className="bg-blue-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=2" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
<Section sectionID="orange" className="bg-orange-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=3" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
<Section sectionID="pink" className="bg-pink-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=4" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
</>
);
};
export default Home;
You should (almost) never ever ever declare a component inside of another functional component. Doing so essentially creates an entirely new React component class every render, which means it is impossible for React to reconcile which component is which between renders. Try moving your <Section> functional component definition out of the scope of <Home>.
Related
I have a problem with the autoplay video background on the Safari desktop.
AutoPlay works fine in Firefox, Chrome etc, but not in Safari, how can I fix it?
Bellow my code:
<header class="relative flex items-center justify-center h-screen mb-12 overflow-hidden">
<div class="relative z-30 p-5 text-2xl text-white bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<video autoplay loop muted class="absolute z-10 w-auto min-w-full min-h-full max-w-none">
<source src="https://assets.mixkit.co/videos/preview/mixkit-set-of-plateaus-seen-from-the-heights-in-a-sunset-26070-large.mp4" type="video/mp4" />Your browser does not support the video tag.
</video>
</header>
<div class="max-w-lg m-auto">
<p class="mb-4">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec placerat a
magna non varius. Proin leo felis, euismod non porta eget, varius sit amet
sapien. Maecenas in nulla at leo convallis consectetur id a sapien. Nulla
nec pulvinar nisi. Vivamus non facilisis lacus, et volutpat libero. Nulla ac
odio aliquam, accumsan arcu ut, lacinia est. Nulla eu sem elit. Fusce nec
laoreet sem, semper molestie libero.
</p>
<p class="mb-4">
Ut sagittis lacus consequat accumsan venenatis. Sed sollicitudin, lectus et
fringilla ultrices, dolor nisi scelerisque tortor, vel finibus magna massa
non nunc. Phasellus massa quam, egestas a nisl sed, porta volutpat metus.
Nunc sed elit ac tellus tempor cursus. Suspendisse potenti. Vestibulum
varius rutrum nisl nec consequat. Suspendisse semper dignissim sem viverra
semper. Nulla porttitor, purus nec accumsan pharetra, nisi dolor condimentum
ipsum, id consequat nulla nunc in ligula.
</p>
<p class="mb-12">
Nulla pharetra lacinia nisi, vitae mollis tellus euismod id. Mauris porta
dignissim hendrerit. Cras id velit varius, fermentum lectus vitae, ultricies
dolor. In bibendum rhoncus purus vel rutrum. Nam vulputate imperdiet
fringilla. Donec blandit libero massa. Suspendisse dictum diam mauris, vitae
fermentum dolor tincidunt in. Pellentesque sollicitudin venenatis dolor,
vitae scelerisque elit ultrices eu. Donec eget sodales risus, quis dignissim
neque.
</p>
</div>
Live preview:
https://codepen.io/zdebskimatt/pen/yLqqZdN
ps.
How can I add a static image if the video does not play automatically on desktop, mobile?
I'm currently trying to create a portfolio website as a result of my learnings on Next.js and tailwind.
The problem that I'm facing at the moment is that I'm unable to make my application responsive on a mobile layout. As you can see the image and the texts are overlapping themselves instead of staying in place
I'm still a beginner at web development so I don't really have any idea of how to fix it after 4 frustrating hours trying to align the contents.
Here is the code that I'm trying to implement, any ideas?
import React from 'react'
import { motion } from "framer-motion";
type Props = {}
export default function About({}: Props) {
return (
<motion.div
initial={{ opacity: 0 }}
transition={{ duration: 1.5 }}
whileInView={{ opacity: 1 }}
className='flex flex-col relative h-screen text-center md:text-left md:flex-row max-w-7xl px-10 justify-evenly mx-auto items-center'>
<h3 className='absolute top-24 uppercase tracking-[20px] text-gray-500 text-2xl'>
About
</h3>
<motion.img
initial={{
x: -200,
opacity: 0
}}
transition={{ duration: 1.2 }}
whileInView={{
x: 0,
opacity: 1
}}
viewport={{ once: true }}
src='https://images.pexels.com/photos/1572878/pexels-photo-1572878.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' alt="profile picture"
className='-mb-20 md:mb-0 flex-shrink-0 w-56 h-56 rounded-full object-cover md:rounded-lg md:w64 md:h-95 xl:w-[500px] xl:h-[600px]'
/>
<div className='space-y-10 px-0 md:px-10'>
<h4 className='text-4xl font-semibold'>
Here is a little background
</h4>
<p className='text-base'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel libero
nisi. Cras vel dignissim diam. Etiam varius enim sed libero suscipit
sagittis. Suspendisse varius, mi eu tempor porttitor, ex risus molestie
purus, vitae sagittis mi nisl et justo. Fusce fermentum vitae orci at
blandit. Nunc molestie est non metus porta pharetra. Nunc molestie
pretium felis iaculis faucibus. Sed pretium venenatis facilisis.
Vivamus vel varius velit. Nullam id odio vitae ligula efficitur
semper et nec enim. Duis convallis risus eget metus tristique,
pretium elementum eros pharetra. Nulla facilisi. In at mauris
id est ultrices ac
</p>
</div>
</motion.div>
)
}
I am new to React and I am learning the basics, but right now I need to rewrite a Class component in order to use React Hooks. So I guess I need to rewrite it to a functional component.
I already tried changing some of the things but in the end everything breaks and I will get a 'props not defined' error.
This is the code:
class Main extends React.Component {
render() {
let close = (
<div
className="close"
onClick={() => {
this.props.onCloseArticle()
}}
></div>
)
return (
<div
ref={this.props.setWrapperRef}
id="main"
style={this.props.timeout ? { display: 'flex' } : { display: 'none' }}
>
<article
id="vision"
className={`${this.props.article === 'vision' ? 'active' : ''} ${
this.props.articleTimeout ? 'timeout' : ''
}`}
style={{ display: 'none' }}
>
<h2 className="major">Vision</h2>
<span className="image main">
<img src={pic01} alt="" />
</span>
<p>
Adipiscing magna sed dolor elit. Praesent eleifend dignissim arcu,
at eleifend sapien imperdiet ac. Aliquam erat volutpat. Praesent
urna nisi, fringila lorem et vehicula lacinia quam. Integer
sollicitudin mauris nec lorem luctus ultrices.
</p>
<p>
Nullam et orci eu lorem consequat tincidunt vivamus et sagittis
libero. Mauris aliquet magna magna sed nunc rhoncus pharetra.
Pellentesque condimentum sem. In efficitur ligula tate urna.
Maecenas laoreet massa vel lacinia pellentesque lorem ipsum dolor.
Nullam et orci eu lorem consequat tincidunt. Vivamus et sagittis
libero. Mauris aliquet magna magna sed nunc rhoncus amet feugiat
tempus.
</p>
{close}
</article>
</div>
)
}
}
Main.propTypes = {
route: PropTypes.object,
article: PropTypes.string,
articleTimeout: PropTypes.bool,
onCloseArticle: PropTypes.func,
timeout: PropTypes.bool,
setWrapperRef: PropTypes.func.isRequired,
}
export default Main
What I did is changing class main to const Main = () => {, remove the render() but after that I am confused..
This should do the work
Replace class by const
Remove the render lifecycle method used in class components
Add the props in the parameter of the function
Remove all the this
const Main = (props) => {
let close = (
<div
className="close"
onClick={() => {
props.onCloseArticle()
}}
></div>
)
return (
<div
ref={props.setWrapperRef}
id="main"
style={props.timeout ? { display: 'flex' } : { display: 'none' }}
>
<article
id="vision"
className={`${props.article === 'vision' ? 'active' : ''} ${
props.articleTimeout ? 'timeout' : ''
}`}
style={{ display: 'none' }}
>
<h2 className="major">Vision</h2>
<span className="image main">
<img src={pic01} alt="" />
</span>
<p>
Adipiscing magna sed dolor elit. Praesent eleifend dignissim arcu,
at eleifend sapien imperdiet ac. Aliquam erat volutpat. Praesent
urna nisi, fringila lorem et vehicula lacinia quam. Integer
sollicitudin mauris nec lorem luctus ultrices.
</p>
<p>
Nullam et orci eu lorem consequat tincidunt vivamus et sagittis
libero. Mauris aliquet magna magna sed nunc rhoncus pharetra.
Pellentesque condimentum sem. In efficitur ligula tate urna.
Maecenas laoreet massa vel lacinia pellentesque lorem ipsum dolor.
Nullam et orci eu lorem consequat tincidunt. Vivamus et sagittis
libero. Mauris aliquet magna magna sed nunc rhoncus amet feugiat
tempus.
</p>
{close}
</article>
</div>
)
}
I create this code:
import React from 'react'
import { range } from 'lodash'
const DIV_NUMBER = 5
export default class App extends React.Component {
constructor(props) {
super(props)
this.divs = []
}
handleScroll = divIdx => () => {
const divRef = this.divs[divIdx]
const left = divRef.scrollLeft
const top = divRef.scrollTop
this.divs.forEach(div => (div.scrollLeft = left))
this.divs.forEach(div => (div.scrollTop = top))
}
render() {
return (
<div style={{ border: '1px solid tomato' }}>
{range(DIV_NUMBER).map(i => {
return (
<div
key={i}
ref={divElem => (this.divs[i] = divElem)}
onScroll={this.handleScroll(i)}
style={{
width: 300,
height: 100,
margin: '2px',
overflow: 'auto',
border: '1px solid black',
}}
>
<div
style={{
width: 500,
height: 400,
}}
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Scelerisque eu ultrices vitae auctor eu
augue ut lectus. In fermentum et sollicitudin ac orci. Velit sed ullamcorper morbi
tincidunt ornare. Auctor eu augue ut lectus arcu bibendum. Non nisi est sit amet.
Facilisis magna etiam tempor orci eu lobortis. Et tortor at risus viverra adipiscing
at in tellus integer. Lacus luctus accumsan tortor posuere ac ut consequat semper
viverra. Fermentum dui faucibus in ornare quam viverra orci sagittis. Porttitor eget
dolor morbi non. Pulvinar pellentesque habitant morbi tristique senectus et.
Tincidunt eget nullam non nisi est sit amet facilisis magna. Purus semper eget duis
at tellus at urna condimentum. Ipsum dolor sit amet consectetur adipiscing. Sit amet
aliquam id diam maecenas ultricies mi eget mauris. Faucibus scelerisque eleifend
donec pretium vulputate sapien nec sagittis. Tristique senectus et netus et
malesuada fames ac turpis. Egestas integer eget aliquet nibh. Enim ut tellus
elementum sagittis vitae. Urna condimentum mattis pellentesque id nibh tortor id
aliquet. Magna eget est lorem ipsum dolor. Felis imperdiet proin fermentum leo vel
orci porta. Eget egestas purus viverra accumsan in nisl nisi. Adipiscing commodo
elit at imperdiet. Facilisis magna etiam tempor orci eu lobortis. Volutpat est velit
egestas dui id ornare arcu odio. Praesent elementum facilisis leo vel fringilla.
Laoreet non curabitur gravida arcu ac tortor dignissim convallis aenean. Sodales ut
etiam sit amet nisl. Turpis massa tincidunt dui ut ornare. Viverra mauris in aliquam
sem fringilla ut morbi tincidunt augue.
</div>
</div>
)
})}
</div>
)
}
}
It works.
It creates 5 div elements, scrolling one of them, all the div scroll togheter. I use React references to do that.
What I would like to do now is creates a component that abstracts this logic.
I imagine something like that:
<ScrollDivs>
{range(DIV_NUMBER).map(i => {
return (
<div
key={i}
style={{
width: 500,
height: 400,
}}
>
all the text...
</div>
)
})}
</ScrollDivs>
So a magic component ScrollDivs that deals with logic.
Who uses this component does not have to worry about how it is done, he just needs to wrap the divs that wants to be able to scroll together inside this component.
How can I do? I don't know where to start.
Any help is appreciate
React.Children.map can help you to iterate over props.children and React.cloneElement can help with passing new props to children:
export default class ScrollDivsSync extends React.Component {
divs = [];
handleScroll = e => {
const { scrollTop, scrollLeft } = e.target;
this.divs.forEach(div => {
div.scrollLeft = scrollLeft;
div.scrollTop = scrollTop;
});
};
render() {
const { children } = this.props;
let i = 0;
const enhancedChildren = React.Children.map(children, child =>
React.cloneElement(child, {
onScroll: this.handleScroll,
ref: divElem => (this.divs[i++] = divElem)
})
);
return enhancedChildren;
}
}
This is a CodeSandbox with the example
I recently had to pick up ReactJS in the last few days to work on a project. While I have most of the basics down, I'm coming across issues with the syntax of ES5 and ES6. I can't quite grasp the differences and how to convert code from one to the other. I've been using a lot of copy and paste of ES6, so it's been fairly easy for me to pick up. But when I come across ES5, I struggle.
I'm trying to create a modal from pre-existing code, but I don't quite know what it's supposed to look like in the end. Here is what I'm trying to convert:
import React from 'react';
import ReactDOM from 'react-dom';
const Example = React.createClass({
getInitialState() {
return { showModal: false };
},
close() {
this.setState({ showModal: false });
},
open() {
this.setState({ showModal: true });
},
render() {
const popover = (
<Popover id="modal-popover" title="popover">
very popover. such engagement
</Popover>
);
const tooltip = (
<Tooltip id="modal-tooltip">
wow.
</Tooltip>
);
return (
<div>
<p>Click to get the full Modal experience!</p>
<Button
bsStyle="primary"
bsSize="large"
onClick={this.open}
>
Launch demo modal
</Button>
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>
<h4>Text in a modal</h4>
<p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula.</p>
<h4>Popover in a modal</h4>
<p>there is a <OverlayTrigger overlay={popover}>popover</OverlayTrigger> here</p>
<h4>Tooltips in a modal</h4>
<p>there is a <OverlayTrigger overlay={tooltip}>tooltip</OverlayTrigger> here</p>
<hr />
<h4>Overflowing text to show scroll behavior</h4>
<p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
<p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
<p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
<p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
<p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
<p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>Close</Button>
</Modal.Footer>
</Modal>
</div>
);
}
});
ReactDOM.render(<Example />, mountNode);
Any tips/tricks/help would be truly appreciated!
If you're building your js bundle using something like webpack, you can pick and choose what features of es6 you want to use. it isn't "all or nothing." For example, in the above you're using the ES6 import syntax.
also, an important distinction is the difference between es6 features and React.createClass() and React's extends Component structure. You can read about the here https://facebook.github.io/react/docs/components-and-props.html