Pursuit of Loot

Accordion component

Posted on 27th January 2020

Tags:

A stock image of a man playing an accordion

Inspired by this video by Tyler Potts chosen randomly from my YouTube watch later list - https://www.youtube.com/watch?v=jwp-cYZbgic - I made a small accordion component to use in my site.

There's an example of it over on my Code Experiments page, I know it doesn't look very good but to be honest I was rushing to get this done before the end of the day.

The functionality is there though, so it's something I can probably tweak a bit as and when I use it, like making it optional if all the questions close when a new one is opened, or some different styles for light and dark mode. Maybe even some better animation on the open/close.

In the process of creating the component I found a couple of other sites that would be worth adding to the Useful Links list, so I did that too.

Anyway, that's it for now. If you're curious, the component code is below, note that there are some styles and svg mentioned, I won't include those but you can probably figure it out yourself and make a nicer looking one. If you follow along with Tylers video this will take no time at all!

import React, { useState } from 'react';
import styles from './accordion.module.scss';
import Arrow from '../svg/arrow-down';
const Accordion = () => {
const [questions, setQuestions] = useState(Questions);
const handleClick = index => {
const updatedQuestions = questions.map((question, i) => {
if (i === index) {
question.open = !question.open;
}
return question;
});
setQuestions(updatedQuestions);
};
return (
<div className={styles.accordion}>
<ul>
{questions.map((question, index) => {
return (
<li
key={index}
onClick={() => handleClick(index)}
className={
question.open === true ? styles.open : null
}
>
<div className={styles.question}>
{question.question}
<Arrow />
</div>
<div className={styles.answer}>
{question.answer}
</div>
</li>
);
})}
</ul>
</div>
);
};
export default Accordion;
const Questions = [
{
question: 'foo',
answer: 'bar',
open: false
},
...
];

šŸ™ Special Thanks

Kudos for the photo by Lex Aliviado on Unsplash, keep up the great work!


Enjoyed this post? Feel free to share it with your audience using the links below:

Don't see your favourite social network on the list? Feel free to let me know and I'll get it added.

Comments

Ā©2022 Pursuit of Loot. All rights reserved.