Creating a Reusable Component
In our previous blog post, we discussed creating a reusable component for Input and Button. Now we are going to see how to create a reusable component for collapse and carousel
- Collapse Component
- Carousel Component
Collapse Component
The purpose of creating a collapse component is components that should serve as a collapse for multi-style (Single Collapse, Multiple Collapse and Multiple Collapse Horizontal). While creating this component we will be using Fragment and react-bootstrap which is available in react.
Purpose of using fragment
Fragments will be used in react to group the list of child nodes without adding an extra node to the DOM. This function will help you to avoid using unnecessary div tag while building components
Purpose of using react-bootstrap
React Bootstrap (react-bootstrap) is a third party NPM Module which has all the bootstrap module inbuilt. So you can use the module which you need. This package will reduce your effort of writing your own code for all the bootstrap component you need
● Prerequisites
Believe you have already completed the react installation process. If not, please follow the steps mentioned here
● Create Folder
Create Collapse folder inside component folder (src > Component > Collapse > Collapse.js ) and create a Collapse.js file inside Collapse folder
● Importing the Required Files
We have to use Hooks feature to write the components. To write the react collapse component first we need to import react, collapse and custom button (Button component we created in previously).
import React from ‘react’;
import { Collapse } from ‘react-bootstrap’
import { Button as CustomButton } from ‘./Button’
● Reusable Function
Write functional to get props and use the props to generate a reusable component
import React, {Component, useState, Fragment} from ‘react’;
import { Collapse } from ‘react-bootstrap’
import { Button as CustomButton } from ‘./Button’
import {Link} from ‘react-router-dom’
export function SingleCollapse(props) {
const [open, setOpen] = useState(props.open);
return (
<Fragment>
<CustomButton type=”button” onClick={() => setOpen(!open)} className=”btn-primary” text=”click” />
<Collapse in={open}>
<div id=”example-collapse-text”>
{props.children}
</div>
</Collapse>
</Fragment>
);
}
export function CollapseMultiple(props){
return(
<div id=”accordion”>
<div className=”card”>
{props.data.map((data, i)=>{
return <Fragment>
<div className=”card-header” key={i}>
<h5 className=”mb-0″>
{ data.buttontext &&
<Link onClick={()=>props.clickfunction(i)} aria-controls=”example-collapse-text” text={data.buttontext} >
{data.buttontext}
</Link>
}
</h5>
</div>
<Collapse in={data.open}>
<div className=”card-body”>
{data.content}
</div>
</Collapse>
</Fragment>
})
}
</div>
</div>
);
}
Note : Copy this code and past this in (src > component > Collapse > Collapse.js ) Collapse.js file
● How to use this Collapse Component
We have created a reusable collapse component, now we need to use this component in pages to see how it works.
To use this Collapse component we need to create a file container folder
(src > Container > From > Collapse.js ) and name it as Collapse.js.
Follow the steps to use this component
● Import the Component and Required Modules
- Import react
– importReact,{Component} from “react”; - Import collapse and react-bootstrap
import{ SingleCollapse, CollapseMultiple
} from ‘../../../Component/Collapse’
● Utilizing Collapse Component
You can import the component where it’s necessary and use the collapse component as mentioned below.
<SingleCollapse open={false}><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean viverra consectetur dignissim. Maecenas elementum eros nec faucibus mollis. Nulla vestibulum scelerisque nibh, sit amet ornare augue. Nunc gravida posuere egestas. Morbi laoreet dictum ipsum sit amet tincidunt. Nulla sit amet vestibulum magna. Donec sed elit imperdiet, ultrices turpis eu, vulputate neque. Vestibulum maximus dolor vitae erat eleifend egestas. Donec eget elit dapibus, fringilla sapien at, condimentum mi. Nulla lobortis mauris in purus tempus, eget euismod odio consequat.</p></SingleCollapse>
● Sample Class Component
This Collapse has all the styles imported from bootstrap. So if you need to do any changes with CSS you need to create separate css file and import in this component
import React,{Component} from “react”;
import { SingleCollapse , CollapseMultiple} from ‘../../../Component/Collapse/Collapse’
class CollapseComponent extends Component{
constructor(props){
super(props);
this.handleclick = this.handleclick.bind(this)
this.state = {
open:false,
clickfunction: this.handleclick,
data : [
{content:<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean viverra consectetur dignissim. Maecenas elementum eros nec faucibus mollis. Nulla vestibulum scelerisque nibh, sit amet ornare augue. Nunc gravida posuere egestas. Morbi laoreet dictum ipsum sit amet tincidunt. Nulla sit amet vestibulum magna. Donec sed elit imperdiet, ultrices turpis eu, vulputate neque. </p>,open:true,className:'btn btn-info',buttontext:'Form1'},
{content:<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean viverra consectetur dignissim. Maecenas elementum eros nec faucibus mollis. Nulla vestibulum scelerisque nibh, sit amet ornare augue. Nunc gravida posuere egestas. Morbi laoreet dictum ipsum sit amet tincidunt. Nulla sit amet vestibulum magna. Donec sed elit imperdiet, ultrices turpis eu, vulputate neque. </p>,open:false,className:'btn btn-info',buttontext:'Form2'},
{content:<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean viverra consectetur dignissim. Maecenas elementum eros nec faucibus mollis. Nulla vestibulum scelerisque nibh, sit amet ornare augue. Nunc gravida posuere egestas. Morbi laoreet dictum ipsum sit amet tincidunt. Nulla sit amet vestibulum magna. Donec sed elit imperdiet, ultrices turpis eu, vulputate neque. </p>,open:false,className:'btn btn-info',buttontext:'Form3'},
],
}
}
handleclick=(values)=>{
let updatearr=this.state.data.map((data, i)=>{
if(values===i){
return {…data,open:(data.open==true)?false:true}
}else{
return {…data,open:false}
}
})
this.setState({
open:true,
clickfunction:this.state.clickfunction,
data:updatearr,
})
}
render(){
const { handleSubmit } = this.props;
return(
<div className=”row”>
<SingleCollapse open={false}>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean viverra consectetur dignissim. Maecenas elementum eros nec faucibus mollis. Nulla vestibulum scelerisque nibh, sit amet ornare augue. Nunc gravida posuere egestas. Morbi laoreet dictum ipsum sit amet tincidunt. Nulla sit amet vestibulum magna. Donec sed elit imperdiet, ultrices turpis eu, vulputate neque. Vestibulum maximus dolor vitae erat eleifend egestas. Donec eget elit dapibus, fringilla sapien at, condimentum mi. Nulla lobortis mauris in purus tempus, eget euismod odio consequat.</p>
</SingleCollapse>
<CollapseMultiple {…this.state}/>
</div>
);
}
}
export default CollapseComponent
Note : Copy this code and paste this in (src > Container > From > Collapse.js ) Collapse.js file
● Collapse Component Preview
After creating Collapse class component you can run the react file and see the following output
Carousel Component
Purpose of creating Carousel component is that component should serve as slider and can be reused by passing required parameters (image URL and slider name)
● Prerequisites
Believe you have already completed the react installation process. If not, please follow the steps mentioned here.
● Create Folder
Create form folder inside component folder (src > Component > Carousel > Carousel.js ) and create a Carousel.js file inside From folder
● Importing the Required Files
We have used Hooks feature to write the components. To write the react carousel component first, we need to import react and Carousel from react-bootstrap’.
import React from ‘react’;
● Reusable Function
Write functional to get props and use the props to generate a reusable component
import React, {Component, useState} from ‘react’;
import { Carousel } from ‘react-bootstrap’
export function CarouselComponent(props){
return(
<Carousel {…props}>
{props.data.map((data, i)=>{
return <Carousel.Item key={i}>
<img
className=”d-block w-100 carousel-img”
src={data.image}
alt=”First slide”
/>
<Carousel.Caption>
<h3>{data.caption}</h3>
</Carousel.Caption>
</Carousel.Item>
})}
</Carousel>
);
}
Note : Copy this code and paste this in (src > Component > Carousel > Carousel.js ) Carousel.js file
Above code will generate a slider with the image url and slide name you provided
● How to use this Carousel Component
We have created a reusable Carousel component now we need to use this component in some pages to see how it works.
To use this Carousel component we need to create a file container folder (src > Container > From > Carousel.js ) and name it as Carousel.js.
Follow the steps to use this component
● Import the Component and Required Modules
- Import react
– importReact,{Component} from “react”; - Import the Carousel that we created
– import{ CarouselComponent } from ‘../../../Component/Carousel/Carousel’
● Utilizing Carousel Component
You can import the component where nessay and use the Carousel component as mentioned below .
<CarouselComponent data={this.state.data} fade={true}/>
● Sample Class Component
This carousel have all the styles imported from bootstrap. So if you need to do any changes with css you need to create separate css file and import in this component
import React,{Component} from “react”;
import { CarouselComponent } from ‘../../../Component/Carousel/Carousel’
class CarouselClassComponent extends Component{
constructor(props){
super(props);
this.state={
fade:”true”,
data:[
{image:’https://via.placeholder.com/400×155.png?text=Slider1′,caption:’Banner 1′},
{image:’https://via.placeholder.com/400×155.png?text=Slider2′,caption:’Banner 2′}
],
}
}
render(){
const { handleSubmit } = this.props;
return(
<div className=”row”>
<div label=”Reference”>
<div class=”descriptions”>
<h2>Carousel Component</h2>
<p>
The carousel is a slideshow for cycling through a series of content, built with CSS 3D transforms and a bit of JavaScript. It works with a series of images, text, or custom markup. It also includes support for previous/next controls and indicators.
</p>
</div>
<div class=”bd-example”>
<CarouselComponent data={this.state.data} fade={true}/>
</div>
</div>
</div>
);
}
}
export default CarouselClassComponent;
Note : Copy this code and past this in (src > Container > From > Carousel.js ) Carousel.js file
● Carousel Component Preview
After creating a Carousel class component you can run the react file and see the following output
Installations
To write reusable component with react and redux you need to install following npm module
- npm install -g create-react-app
-g is used to install the npm module globally this will make the module and –save is used while to save the installed module in package.json file.
Once after installing create-react-app run following commands to create a react project
- Create-react-app reusable-component
The above command will create a reusable-component that bundled with inbuilt npm modules such as react, react-dom. We need some more modules to create reusable components.
Install the following module to create more reusable components
- npm install –save react-redux
- npm install –save redux
- npm install –save bootstrap
- npm install –save reactstrap
After installing this module you need to import required function from the module to that make it easy to use
Folder Structure In React
There is no predefined structure in react projects. It’s your idea to format the folders. Here we mentioned the best practices folder structure. We have split components into a container and presentational component according to the component usage which makes it easy to use.