Create custom React js Accordion component
Creating components in react can be tricky for beginners. I have done some of my projects in react and the scope of some of those projects are small, so using external components library can make the project comparatively heavy. Instead I decided to create my own components and use them. In this article i am going to show you guys how i create my own accordion component in React js.
So before starting the development, I was thinking of the steps to proceed. I was thinking of how to go forward. so here are the basic steps of development i though of while i was creating this component.
- create a tab structure which contains a title and content section.
- when i click on title, the content below will expand.
- when this happens any other section which is expanded will close simultaneously.
Basically, we will create an accordion class in which we will populate the tabs from the tab data recieved in an array. Inorder to do that, we will further define a tab component which will show the tab title and tab content.
So let’s get started!!
Defining accordion class
First we will create the base accordion class which will be the react component as follows:
As you can see, I have looped through the tabs array and rendered a Tab component in which i am passing tab data. As you add this structure, you will get an error as the <Tab /> component is not defined. Let’s ,get to it and define out Tab component.
Defining tab component class
Now let’s define the Tab component in which we will render the tab title and tab conetent. Add the following :
now the tab structure is ready , lets add some styling to the tabs so that it will have the look of an accordion. add the following scss :
At this point, the accordion component is ready and you will fint he following output:
But when you try and click on the tab , you will se that the accordion is not functional yet as the client method has not been defined and added yet. so let’s do that now.
Handling the functionality
Inorder to get the accordion working, when the user clicks on the tab title, the tab component should pass the data i.e which tab is currently active to its parent i.e the accordion component.
We need to add a method which will update the active tab status and based on that status the accordion will render accordingly.
add the method in accordion class as follows:
Along with that add the click method in your tab class to tab title container as follows:
If all the steps are followed properly, you will find your accordion working as shown in the fiddle below:
I will be creating more components like this and share with you guys in the coming articles. If you have any doubts or any suggestions let me know in the comments section below.228