React native calendar: Simple steps to create this component

In this digital world, the professional and personal lifestyles of humans have changed since the last two decades. Our lives have not only become faster, but also hectic as we have to cope with so many things. And that’s when React Native comes to life. It is certainly one of the most effective JavaScript frameworks that can boost the development experience to a whole new level. The components are the make-over of this framework and the React native calendar is also of no exception.

React native calendar creation
React native calendar creation

Having a calendar application can not only help you plan better schedules but also make you aware of all the upcoming events and due dates during the month. Therefore, this post will explain building the React-native-calendars component in the most basic steps, so that you guys can fully implement it for your project. So, without wasting any more time, let’s get into the step-by-step tutorial for creating React-native-calendars

Step 1: Creating a New Project

With React-native-calendars programming language, it is obviously required to install a couple of reliable files and software inside your system to create all the necessary dependencies to build your application. Therefore, we will use the simplest way to create a calendar component in React Native. To clarify, we are going to use an all-in-one IDE that will have no additional setup, thanks to its plug-and-play feature.

Then, the IDE will take just a few seconds to create your project and prepare a preview device for it. Once it’s ready, it should look like this:

React native calendar example
React native calendar example

Step 2: Creating new components

To be able to use the React framework and React-native-calendars components in your project, add the following import statements at the beginning of the App.js file:

 import * as React from 'react';
import * as RN from 'react-native';

You should then create a custom React component by creating a class that extends the Component class. Inside the class, you must also add a method named render(), which returns JSX code. The following code creates a component named MyCalendar:

 class MyCalendar extends React.Component {
  render() {
    return (
      <RN.View>

      </RN.View>
    );
  }
}

In the render() method, we’re returning an empty View component instead. It’s obviously going to serve as a container for all the other components of our calendar.

Step 3: Creating constants when developing your React native calendar component

The React-native-calendars component certainly needs two string arrays: one to store the names of the months and one to store the names of the days of the week.

 months = ["January", "February", "March", "April", 
"May", "June", "July", "August", "September", "October", 
"November", "December"];

weekDays = [
    "Sun","Mon","Tue","Wed","Thu","Fri","Sat"
];

Then, we’ll need an array that stores the number of days each month has. So, for February, let the number be 28. We’ll write the code to handle leap years later.

nDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

Step 4: Initialize a state for your React native calendar

To make our React-native-calendars component interactive, we must certainly associate a state with it. For now, we’re going to store nothing but a Date object inside the state, initialized to today’s date.

 state = {
    activeDate: new Date()
}

The state, of course, is mutable. When a user clicks on a different date in the calendar, we’ll be changing the state to use the new date.

Step 5: Locating the first day of the month

To do so for your React-native-calendars, first, get the year and month of the Date object stored in the state. Then create a new Date object using those values and 1, the first day of the month. By calling the getDay() method of this new object, you should obviously get the first day of the month.

 var year = this.state.activeDate.getFullYear();
var month = this.state.activeDate.getMonth();

var firstDay = new Date(year, month, 1).getDay();

Also, we can’t directly use the nDays array to determine the number of days the current month has on the React-native-calendars. If the month’s February, we need to manually add an extra day while dealing with leap years. So here’s how:

 var maxDays = this.nDays[month];
if (month == 1) { // February
  if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
    maxDays += 1;
  }
}

Step 6: Add names of months for your React native calendar

Our calendar should certainly be able to highlight today’s date or the date the user selects. Therefore, let’s associate a fontWeight property with each Text component. We’ll set it to bold whenever its contents match the date in our state’s activeDate variable. So, let’s display the year and the name of the current month by adding a Text component to the currently empty View component. What’s more, you can use the style prop to add styles to the text.

 <RN.Text style={{
  fontWeight: 'bold',
  fontSize: 18,
  textAlign: 'center'
}}>
  {this.months[this.state.activeDate.getMonth()]}  
  {this.state.activeDate.getFullYear()}
</RN.Text>

The following code shows you how to use the map() method as an alternative to for loops while generating a component hierarchy for the contents of the matrix of the React-native-calendars:

 var rows = [];
rows = matrix.map((row, rowIndex) => {
  var rowItems = row.map((item, colIndex) => {
    return (
      <RN.Text
        style={{
          flex: 1,
          height: 18,
          textAlign: 'center',
          // Highlight header
          backgroundColor: rowIndex == 0 ? '#ddd' : '#fff',
          // Highlight Sundays
          color: colIndex == 0 ? '#a00' : '#000',
          // Highlight current date
          fontWeight: item == this.state.activeDate.getDate() 
                              ? 'bold': ''
        }}
        onPress={() => this._onPress(item)}>
        {item != -1 ? item : ''}
      </RN.Text>
    );
  });
  return (
    <RN.View
      style={{
        flex: 1,
        flexDirection: 'row',
        padding: 15,
        justifyContent: 'space-around',
        alignItems: 'center',
      }}>
      {rowItems}
    </RN.View>
  );
});

Step 7: Sync months with dates when using your React native calendar

Firstly, create a setMonth function.

 setMonth = month => {  
let monthNo = this.months.indexOf(month);// get month number  
let dateObject = Object.assign({}, this.state.dateObject);  
dateObject = moment(dateObject).set("month", monthNo); // change month value  
this.setState({  
dateObject: dateObject // add to state  
});  
};  

Then, add it to <td>

 props.data.map(data => {  
months.push(  
<td  
key={data}  
className="calendar-month"  
onClick={e => {  
this.setMonth(data);  
}}  
>  
<span>{data}</span>  
</td>  
);  
});  

Now, whenever you click on the name of the month, the calendar should change accordingly, along with the right dates. The table of month picker is currently creating redundancy and also, not required to be there all the time.

Step 8: Changing months

Our React-native-calendars component will certainly have two buttons labeled Next and Previous. These buttons, when pressed, should allow users to move from one month to another. As you may have guessed, inside their event handlers, all we need to do instead is get the activeDate object and increment or decrement its month by 1.

Accordingly, add the following code towards the end of the JSX returned by the render() method:

 <RN.Button title="Previous"
        onPress={() => this.changeMonth(-1)}/>
<RN.Button title="Next"
        onPress={() => this.changeMonth(+1)}/>

After that, create the changeMonth() method. Inside it, you must first call the setState() method and then call the setMonth() method to update the activeDate object on the React-native-calendars.

 changeMonth = (n) => {
    this.setState(() => {
      this.state.activeDate.setMonth(
        this.state.activeDate.getMonth() + n
      )
      return this.state;
    });
}

Step 9: Using the Component

Our React-native-calendars component is indeed almost ready. In order to use it, just add it to the render() method of your App class.

 export default class App extends React.Component {
  render() {
    return <MyCalendar/>;
  }
}

And we’re all set!

Final words

So, that may conclude the simple steps on how to create React-native-calendars component for your eCommerce project. All in all, you now should know how to create and use a custom calendar component without depending on any third-party packages. The component you created today is obviously interactive, extensible, and can be used in any app with minimal changes. As a result, you should feel free to add more styles and functionality to it. 

Above are all information about Simple steps to create React-native-calendars component. In case you are any ideas or questions. So feel free to ask us at CONTACT FORM. Please note that ArrowHiTech also provides React Native app development services . Thus, don’t miss it. We believe that our services will help to be success in your business.

Tags

Share