• Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
No Result
View All Result

Dynamic accordion menu using ReactJs Tutorial

by Shashank Tiwari
March 2, 2019
in ReactJs
2
4 Minutes Read
Dynamic accordion menu using ReactJs Tutorial

You are creating a Website using ReactJs and you have FAQ Page or a Page where you want to show a large amount of content. If you will display the details straight to the page, it will be too long for anyone to read and honesty no one would like to read the information that you are providing. So today we will create a Dynamic accordion menu using ReactJs.

Yes, Here Accordion comes to the rescue. One can simply categories the data and show them as a Pills, Tabs or Accordion. But here we will focus on Accordion only and we will create it in Reactjs. Okay, so enough talking let’s get our hands dirty.

 




 

 Download

1. Starting off with create-react-app

Let’s create a React app usingcreate-react-app CLIto create new React app.This CLI is actually built by Facebook for developers to create a well structured React application.

To install the create-react-app tool use the below command:

npm install -g create-react-app

Once you do so use below command to create a new application:

reate-react-app accordion

Now this command will create a new folder called accordion and download the all necessary dependencies. To run the application in development mode you should usenpm startand run the application in production mode you should usenpm run build.

Since we are creating a dynamic accordion, we willaxiosto fetch data from the mock API server, just to generate fake data. You can installaxiosusing npm , Below is my package.json file:

package.json:

{
  "name": "accordion",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.17.0",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-scripts": "1.0.17"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

I normally prefer to create my all components in a separate folder.Here I have created a folder named as component and I will create my accordion component inside it. Below is our project’s folder structure.

 

Dynamic accordion menu using ReactJs2. Creating a Dynamic accordion menu using ReactJs

Here we will create two filesAccordion.js,Section.jsand We will useApp.jsandindex.csscreated by create-react-app CLI. Let’s start off by modifying App.js:

App.js:

/* 
* Dynamic accordion menu using ReactJs Tutorial
* @author Shashank tiwari 
*/
import React, { Component } from 'react';
import './App.css';
import Accordion from './components/Accordion';


class App extends Component {
  render() {
        return (
            <Accordion/>
        );
    }
}

export default App;

Explanation:

Nothing too fancy here, I have just imported Accordion component and that’s it.

3. Generating a Fake data and calling Accordion

Let’s write something inside theAccordion.js, In this component, we will call another component named as Section. The Section component is part of Accordion component.

Accordion.js:

/* 
* Dynamic accordion menu using ReactJs Tutorial
* @author Shashank tiwari 
*/import React from 'react';
import axios from 'axios';

import Section from './Section';


class Accordion extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            posts: null,
            loading: true,
            error: null
        };
    }

    componentDidMount() {
        /*
        * Using axios to fetch the data from API
        */        axios.get(`https://jsonplaceholder.typicode.com/posts`)
            .then(res => {
                /*
                * If everything goes all good, Then setting up the state of the application.
                */                const posts = res.data;

                this.setState({
                    posts,
                    loading: false,
                    error: null
                });
            })
            .catch(err => {
                /*
                * If Something goes wrong, Saving the errors in state and re-rendering it.
                */                this.setState({
                    loading: false,
                    error: true
                });
            });
    }

    /*
    * Method to render the loading screen
    */    renderLoading() {
        return (
            <div className="accordion-container">
                <h1 className="error">Loading...</h1>
            </div>
        );
    }

    /*
    * Method to render the Error Message
    */    renderError() {
        return (
            <div>
                Something went wrong, Will be right back.
            </div>
        );
    }

    /*
    * Method to render the users with checkbox
    */    renderPosts() {
        const { posts, loading, error } = this.state;

        /*
        * Calling the renderError() method, if there is any error  
        */        if (error) {
            this.renderError();
        }

        return (
            <div className="accordion-container">
                <h1>Accordion Component</h1>
                {posts.map(post =>
                    <Section post={post} key={post.id} />
                )}
            </div>
        );
    }

    render() {

        /*
        * Using destructuring to extract the 'error' from state.
        */
        const { loading } = this.state;
        return (
            <div>
                {loading ? this.renderLoading() : this.renderPosts()}
            </div>
        );
    }

}

export default Accordion;

Explanation:

1.Imports:- We have three imports here first two are the node modules and the Third one is<Section>component.

2.constructor(props):-Inside the constructor method, there’s stats and props And If you work with React I assume you are familiar with it.

3.componentDidMount():- We will generate fake data from Mock REST API.

4.renderLoading():- This method will render the Loading Text till the previous method gets data from Mock API server.

5.renderError():- This method will render the error message on the Page.

6.renderPosts():- This method will call the<Section/>component and render the Accordion in a Loop.

4. Displaying the Accordion

Now open theSection.jsand write down the below code. In the<Section/>component, we will handle the hide and show part of Accordion. As I said earlier the<Section/>component will be called by Accordion component in a loop.

Section.js:

/* 
* Dynamic accordion menu using ReactJs Tutorial
* @author Shashank tiwari 
*/
import React from 'react';

class Section extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            open: false,
            className: 'accordion-content accordion-close',
            headingClassName: 'accordion-heading'
        };

        this.handleClick = this.handleClick.bind(this);
    }

    /*
    * Handling the click event
    */    handleClick() {
        const { open } = this.state;
        if (open) {
            this.setState({
                open: false,
                className: "accordion-content accordion-close",
                headingClassName: "accordion-heading"
            });
        } else {
            this.setState({
                open: true,
                className: "accordion-content accordion-open",
                headingClassName: "accordion-heading clicked"
            });
        }
    }

    /*
* Ceating the single accordion here.
*/    render() {

        /*
        * Using destructuring to extract the 'error' from state.
        */        const post = this.props.post;
        const { className } = this.state;
        const { headingClassName } = this.state;
        return (
            <div className="parent-accordion">
                <div className={headingClassName} onClick={this.handleClick}>
                    {post.title}
                </div>
                <div className={className}>
                    {post.body}
                </div>
            </div>
        );
    }

}

export default Section;

Explanation:

ThehandleClick()method will add and remove the class name from the Elements. The render method() will return the single Accordion along with hiding and show functionality and So now we have successfully implemented Dynamic Accordion using ReactJs.

 

Tags: Accrodian MenuReact
Previous Post

Adult content moderation using NodeJs

Next Post

Creating single page React app using React Router Dom

Related Posts

Show better loading screen in React using Suspense and SuspenseList
ReactJs

Show better loading screen in React using Suspense and SuspenseList

May 1, 2020
Real time private chatting app using React, Nodejs, mongodb and Socket.io – Part 4
ReactJs

Real time private chatting app using React, Nodejs, mongodb and Socket.io – Part 4

October 31, 2019
Real time private chatting app using React, Nodejs, mongodb and Socket.io banner
ReactJs

Real time private chatting app using React, Nodejs, mongodb and Socket.io – Part 3

October 20, 2019
Next Post
Creating single page React app using React Router Dom

Creating single page React app using React Router Dom

Comments 2

  1. pintan jena says:
    6 years ago

    can u send me the css for this accordion application

    Reply
    • Shashank Tiwari says:
      6 years ago

      Hi there,
      Here is link to download the source code. I haven’t updated the source for a long time, so things might not work as expected.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




https://codershood.info

www.codershood.info programming blog dedicated to providing high-quality coding tutorial and articles on web development, Angular, React, Laravel, AngularJs, CSS, Node.js, ExpressJs and many more. We also provide ebook based on complicated web application along with the source code.

  • Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.

No Result
View All Result
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.