I am attempting to make a component carousel in React using Framer Motion. The children of AnimatePresence
need a key, so I decided to pass a page state as the key. However, doing this makes the component I am trying to render duplicate. I thought it was because the key would eventually be re-used, so I made a function that generates a random string to use as the key, but that duplicates the component as well.
Component using carousel
const ProjectList = props => {
const [page, setPage] = useState(0);
const projects = [
<Project
name="Example"
desc="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Libero nunc consequat interdum varius sit amet."
image={require("../img/exampleproject.png")}
/>,
<Project
name="Example2"
desc="Another example. This one does nothing too. What a suprise!"
image={require("../img/exampleproject.png")}
/>
]
const genKey = () => {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
const paginate = (newPage) => {
setPage(newPage)
}
return (
<div className="project-list">
<AnimatePresence>
<motion.button key={genKey()} onClick={() => paginate(page-1)}>
<ArrowBackIosIcon/>
</motion.button>
<motion.div key={genKey()} className="project-list"
initial={{opacity: 0}}
animate={{opacity: 1}}
exit={{opacity: 0}}
>
{projects[page]}
</motion.div>
<motion.button key={genKey()} onClick={() => paginate(page+1)}>
<ArrowForwardIosIcon/>
</motion.button>
</AnimatePresence>
</div>
);
I'm not sure how to use libraries like Framer Motion in the snippet editor, so I put it on CodeSandbox
When I don't use a key, it works as expected, however whenever I click one of the arrow buttons it throws the following warnings
P.S I know eventually the page value will go out of range of the length of projects
, I plan on fixing that once I can get this problem sorted.