contacts

(+359) 88 339 4445

Buy All 40 Premium WordPress Themes for $54.99

React.JS Hooks Example

Here is a very simple example of React.JS Hooks: We have an Accordion component with activeIndex state which get updated on Accordion title click:

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.querySelector('#root'));

src/App.js

import React from "react";
import Accordion from "./components/Accordion";

const items = [
  {
    title: "Title 1",
    content: "Content 1",
  },
  {
    title: "Title 2",
    content: "Content 2",
  },
  {
    title: "Title 3",
    content: "Cotent 3",
  },
];

const App = () => {
  return (
    <div>
      <Accordion items={items} />
    </div>
  );
};
export default App;

src/components/Accordion.js

import React, { useState } from 'react';

const Accordion = ({ items }) => {
  const [activeIndex, setActiveIndex] = useState(null);

  const onTitleClick = (index) => {
    setActiveIndex(index);
  };

  const renderedItems = items.map((item, index) => {
    const active = index === activeIndex ? 'active' : '';

    return (
      <React.Fragment key={item.title}>
        <div className={`title ${active}`} onClick={() => onTitleClick(index)}>
          <i className="dropdown icon"></i>
          {item.title}
        </div>
        <div className={`content ${active}`}>
          <p>{item.content}</p>
        </div>
      </React.Fragment>
    );
  });

  return <div className="ui styled accordion">{renderedItems}</div>;
};

export default Accordion;

Leave a Reply