This example shows how to create a simple accordion component.
jsxCopy codeimport React, { useState } from 'react';
import ReactDOM from 'react-dom';
function Accordion() {
const [openIndex, setOpenIndex] = useState(null);
const toggleAccordion = (index) => {
setOpenIndex(openIndex === index ? null : index);
};
const items = [
{ title: 'Section 1', content: 'Content for section 1.' },
{ title: 'Section 2', content: 'Content for section 2.' },
{ title: 'Section 3', content: 'Content for section 3.' },
];
return (
<div>
<h1>Accordion Example</h1>
{items.map((item, index) => (
<div key={index}>
<button onClick={() => toggleAccordion(index)}>
{item.title}
</button>
{openIndex === index && <p>{item.content}</p>}
</div>
))}
</div>
);
}
ReactDOM.render(<Accordion />, document.getElementById('root'));
Leave a Reply