React Accordion
I have found different accordion examples to be pretty boring and with little code you can bring more life to accordions!
We are using framer motion library and also use Tailwind for styling.
npm install tailwind framer-motion
Below is the whole code for the accordion. Just copy and paste it and you have a lively accordion to use on your website!
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
const Accordion = ({ question, answer }) => {
const [isOpen, setIsOpen] = useState(false);
return (
<motion.div>
<AnimatePresence>
<motion.div
key="question"
className="rounded-tr-md relative z-20 rounded-br-md shadow-sm px-1 py-2 bg-blue-200 cursor-pointer font-open border-l-2 border-yellow-500"
onClick={() => setIsOpen(!isOpen)}
>
<motion.div className="text-gray-800 font-bold ml-1">
Do you like animations?
</motion.div>
</motion.div>
{isOpen && (
<motion.div
key="answer"
initial={{ opacity: 0 }}
animate={{
opacity: 1,
transition: {
duration: 0.5,
},
}}
exit={{ opacity: 0 }}
className="p-2 text-lg text-gray-700 border-l border-b border-gray-300"
>
Yes, I love them!
</motion.div>
)}
</AnimatePresence>
</motion.div>
);
};
export default Accordion;
That's it! Simple yet really nice.
Stay around for more free code, drop a follow on twitter where you can ask me any questions and get free resources!
AStylidis
My personal website:
Anargyros Stylidis - Web Developer
Top comments (1)
hi, just stumbled upon this post and let me say thanks for the cool accordion! I have one question, though.. how do you add multiple accordions? I managed to do so by changing the return () to an array [] but now when I open one accordion the other ones open too, lol! I just started with react and nextjs so any help would be appreciated! :)