
One of the most popular front end libraries used now days is React. React is an open-source front end library for building user interface which is mainly used by single-page applications. React was first created by Jordan Walke, a software engineer working for Facebook and it’s deployed on Facebook’s news feed in 2011 and on Instagram.com in 2012.
Features of React JS
- JSX
- Virtual Dom
- Single directional data flow
- Reusable Component
- Hooks
Reusable Component
The reusable component is the heart of the React Application. Building a reusable component will reduce the code size and you can make use of the single logic available wherever you need. There are many npm modules available which are used to write reusable component. Here we will explain how to write a reusable component using reactstrap, redux from, redux
Creating a Reusable Component
In this section, we will create a reusable component for input and button. The first step to create react reusable component is to start with a simple component which will be easy to understand for you
- Date Range Component
Date Range Component
The Date Range component that allows user to select start and end date & time. In this date range component, we can set predefined ranges like ‘This Month’, ‘Last 30 Days’, ‘This Week’ and etc. And also you can use a single date & time selection picker with mentioning in component properties.
● 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 > Form > datepicker.js ) and create a datepicker.js file inside form folder
● Importing the Required Files
We have used Hooks feature to write the components. To write the react component first we need to import react.
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 moment from ‘moment’
import DateRangePicker from ‘react-bootstrap-daterangepicker’;
import { FormControl } from ‘react-bootstrap’
export function Daterange(props){
const [ state, setstate ] = useState(‘All’);
const [ startdate, setstartdate ] = useState(”);
const [ enddate, setenddate ] = useState(”);
const ranges = {
‘All’: [undefined, undefined],
‘Today’: [moment(), moment()],
‘Yesterday’: [moment().subtract(1, ‘days’), moment().subtract(1, ‘days’)],
‘Last 7 Days’: [moment().subtract(6, ‘days’), moment()],
‘Last 30 Days’:[moment().subtract(29, ‘days’), moment()],
‘This Month’: [moment().startOf(‘month’), moment().endOf(‘month’)],
‘Last Month’: [moment().subtract(1, ‘month’).startOf(‘month’), moment().subtract(1, ‘month’).endOf(‘month’)]
}
return(
<div className=”form-group”>
<div className=”form-label”>{props.label}</div>
<DateRangePicker ranges={[]} showWeekNumbers showCustomRangeLabel showDropdowns onApply={props.apply.bind(this)} timePicker={props.timePicker}>
<div id=”reportrange” className=”form-control date-range-picker d-flex position-relative”>
<span style={{ fontWeight: ‘unset’ }}>{props.value}</span>
<i className=”far fa-calendar-alt pr-5px pull-right-position” style={{ float: ‘right’, marginRight:’5px’ }}></i>
</div>
</DateRangePicker>
</div>
)
}
Note : Copy this code and past this in (src > component > form > datepicker.js ) datepicker.js file
● How to use this Date Range Component
We have created a reusable date range component now we need to use this component in some pages to see how it works. To use this select component we need to create a file container folder (src > container > Pags > datepicker.js ) and name it as datepicker.js. Follow the steps to use this component
● Import the Component and Required Modules
- Import react
– importReact,{Component} from “react”; - Import filed and redux form
– import { Field, reduxForm, } from ‘redux-form’; - Import the component that we created
– import { select } from ‘../../../Component/Form/datepicker;
● Utilizing Date Range Component
You can import the component where necessary and use the date range component as mentioned below. You can use this code with bootstrap to get a rich user interface
<div className=”form-group”>
<div className=”form-label”>Date Range Picker</div>
<DateRangePicker ranges={ranges = {‘All’: [undefined, undefined],’Today’: [moment(), moment()],’Yesterday’: [moment().subtract(1, ‘days’), moment().subtract(1, ‘days’)],’Last 7 Days’: [moment().subtract(6, ‘days’), moment()],’Last 30 Days’: [moment().subtract(29, ‘days’), moment()],’This Month’: [moment().startOf(‘month’), moment().endOf(‘month’)],’Last Month’: [moment().subtract(1, ‘month’).startOf(‘month’), moment().subtract(1, ‘month’).endOf(‘month’)]}} showWeekNumbers showCustomRangeLabel showDropdowns onApply={props.apply.bind(this)} timePicker=”true” >
<div id=”reportrange” className=”form-control date-range-picker d-flex position-relative”>
<span style={{ fontWeight: ‘unset’ }}>October 8, 2019 – November 11, 2019</span>
<i className=”far fa-calendar-alt pr-5px pull-right-position” style={{ float: ‘right’,marginRight:’5px’ }}></i>
</div>
</DateRangePicker>
</div>
● Date Range Component Properties
- ranges
- Set predefined date ranges the user can select from. Each key is the label for the range, and its value an array with two dates representing the bounds of the range.
- showWeekNumbers
- Show week numbers at the start of each week on the calendars.
- timePicker
- This property is used to weather have to show time picker also or not it requires boolean true or false value.
- singleDatePicker
- Show only a single calendar to choose one date, instead of a range picker with two calendars; the start and end dates provided to your callback will be the same single date chosen.
- minDate
- Date object, moment object or string) The earliest date a user may select
- maxDate
- (Date object, moment object or string) The latest date a user may select
- Apply
- This is a callback functions this will be triggered after date has been selected.
● Sample Class Component
We have implemented bootstrap with the date range component in below code
import React,{Component} from “react”;
import asyncComponent from ‘../../../Router/async’;
import { Field, reduxForm, SubmissionError } from ‘redux-form’;
import { Daterange , DatePicker } from ‘../../../Component/Form/Datepicker’
import { FormValidation } from ‘../../../validation/forms’
import {renderToString} from ‘react-dom/server’;
const handleFormSubmit=(values)=>{
alert(JSON.stringify(values))
}
class DateRange extends Component{
constructor(props){
super(props);
this.state ={
singledatevalue:”,
preview_data:{
timePicker:”false”,
label:’Date Range’,
singleDatePicker:”false”
},
execute_data:{
timePicker:”false”,
label:’Date Range’,
singleDatePicker:”false”
}
}
}
handleEvent=(event, picker)=>{
if (picker.chosenLabel == ‘All’) {
this.setState({startdate:undefined,enddate:undefined,daterangevalue:’All’})
} else {
this.setState({startdate:picker.startDate,enddate:picker.endDate,daterangevalue:picker.startDate.format(‘MMMM D, YYYY’)+’ – ‘+picker.endDate.format(‘MMMM D, YYYY’)})
}
}
handledatepicker=(event, picker)=>{
console.log(picker.startDate)
//alert(picker.startDate)
this.setState({singledate:picker.startDate,singledatevalue:picker.startDate.format(‘MMMM D, YYYY’)})
}
componentToString(component) {
return <pre>{component}</pre>
}
coverttoString(String) {
return renderToString(String);
}
getdetails(){
let props_sentence=`props:{timePicker:${(this.state.execute_data.timePicker==”true”)?true:false},label:’${this.state.execute_data.label}’}`
return props_sentence;
}
gettabs(){
return this.componentToString(`<Daterange apply={this.handleEvent.bind(this)} value=” label=’${this.state.execute_data.label}’ timePicker=${(this.state.execute_data.timePicker==”true”)?true:false} />`)
}
hadletextboxchange = (e) =>{
let final_value = e.target.value
try {
final_value = JSON.parse(final_value);
this.setState({
preview_data:{
timePicker:final_value.timePicker,
label:final_value.label,
singleDatePicker:final_value.singleDatePicker
}
})
}
catch(error){
alert(error.message)
}
}
handleExecuteClick=()=>{
console.log(‘preview_data’, this.state.preview_data)
this.setState({execute_data:this.state.preview_data})
}
render(){
const { handleSubmit } = this.props;
let status=(this.state.execute_data.timePicker==”true”)?true:false
console.log(‘status’,status)
return(
<div> <div class=”descriptions”>
<h2>Date Range Component</h2>
<p>
Date range component is to render the predefined date based on Today, Yestarday, last week, last month, last year and custom range as a Date range Picker or Single Date picker.
</p>
</div>
<div class=”bd-example”>
<Daterange apply={this.handleEvent.bind(this)} value={this.state.daterangevalue} label=”Date Range Picker” singleDatePicker timePicker={true} />
</div></div>
);
}
}
export default reduxForm({
form:’formcomponent’,
validate:FormValidation
})(DateRange);
Note : Copy this code and past this in (src > Container > Pags > datepicker.js ) datepicker.js file
● Date Range Component Preview
After creating a date range class component you can run the react file and see the following output.
● Single Date Component Preview
For single date selection just change the property to singleDatePicker={true}
Installation
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 bundled with inbuilt npm modules such as react, react-dom. We need some more modules to create reusable components. Install following module
- npm install –save react-redux
- npm install –save redux
- npm install –save bootstrap
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 splitted components into a container and presentational component according to the component usage which makes it easy to use.