What is the best way to set up initial state in react-native-day-picker?

I have been experimenting with implementing react-native-calendar into my project. Here is the code snippet I am working on:

import React from 'react';
import {Calendar} from 'react-native-day-picker';

const MyCalendar = () => {
    var from = new Date();
    from.setDate(from.getDate() - 16);
    var to = new Date();
    var startDate = new Date();
    startDate.setMonth(startDate.getMonth() + 1);

    return (
        <View style={styles.container}>
            <Calendar
                monthsCount={24}
                startFromMonday={true}
                startDate={startDate}
                selectFrom={from}
                selectTo={to}
                width={350}
                onSelectionChange={(current, previous) => {
                    console.log(current, previous);
                }}
            />
        </View>
    );
};

export default MyCalendar;

However, I encountered a Syntax Error and my Project manager has specific requirements that do not align with the current styling approach as shown below:

class XXX extends XXXX {
    constructor(...) {
    }
    render() { ... }
}

The challenge I am facing is initializing values like from, to, and startDate. How should I address this issue?

Answer №1

- Remember not to include a semicolon after tags
- Make sure to return the views in `return(...)`
- You are now able to access myCalender from the class

 const MyCalendar = function () {
        var from = new Date();
     from.setDate(from.getDate() - 16);
     var to = new Date();
     var startDate = new Date();
     startDate.setMonth(startDate.getMonth() + 1);
    return(
    <View style={styles.container}>
                <Calendar
                    monthsCount={24}
                    startFormMonday={true}
                    startDate={startDate}
                    selectFrom={from}
                    selectTo={to}
                    width={350}
                    onSelectionChange={(current, previous) => {
                        console.log(current, previous);
                    }}
                />
            </View>
    );
    };

Answer №2

To handle multiple statements in arrow functions, it is necessary to use block body { }.

For more information on function bodies of arrow functions, you can visit the MDN page.

With a concise body, only an expression is required, while an implicit return is automatically added. In contrast, a block body mandates the use of an explicit return statement.

Hence, ensure that you return the View component as the final statement in your MyCalendar.

I have removed the { } for the onSelectionChange of the Calendar component since a concise body suffices for a single line statement.


Some additional fixes:

For variables where the value is not reassigned, it is advisable to use const.

You may also want to check out the Enforce boolean attributes notation in JSX (jsx-boolean-value) rule from eslint-plugin-react,

When using a boolean attribute in JSX, you can either set the attribute value to true or leave it blank. This rule ensures consistency in your code by enforcing one approach over the other.

This explains my removal of the true value for startFormMonday in the Calendar component.

The updated code looks like this:

const MyCalendar = () => {
  const from = new Date();
  from.setDate(from.getDate() - 16);
  const to = new Date();
  let startDate = new Date();
  startDate.setMonth(startDate.getMonth() + 1);
  return (
    <View style={styles.container}>
      <Calendar
        monthsCount={24}
        startFormMonday
        startDate={startDate}
        selectFrom={from}
        selectTo={to}
        width={350}
        onSelectionChange={(current, previous) => console.log(current, previous)}
      />
    </View>
  );
};

I prefer using Atom text editor and adhere to eslint-config-airbnb for maintaining coding standards and detecting syntax errors efficiently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Crystal-clear TextField component in Office UI Fabric

Seeking advice on how to clear a masked text field from Office UI Fabric using a button. Does anyone have a solution for this? I attempted to set the value using a state, but unfortunately, it did not work as expected. ...

Angular 7: Efficiently Implementing Multiple Cascading Combobox Components

My component is designed to handle the management of cascading countries and states. When I input only one country and state in the form, everything functions perfectly. However, if I input three countries and states, the system malfunctions as shown in th ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

Customizing the colors of the Input field in the Material UI Text Field component with CSS styling can elevate the overall

import { TextField } from "@mui/material"; import { FunctionComponent } from "react"; interface IProps { type: string; label: string; color: | "error" | "primary" | "secondary" | &quo ...

Ways to identify browser version in Angular 4 to discourage IE usage

Is there a method in Angular 4 (TypeScript) for detecting the browser type? I am currently working with Angular 4 and would like to explore options for identifying the browser type when my application is loaded. I specifically want to prevent my applicati ...

Attention: The PageContainer component requires React component classes to extend React.Component

I recently started using react-page-transitions in my project and encountered the following warning message: "PageContainer(...): React component classes must extend React.Component." Here is a snippet of my code: import React from 'react'; ...

The best location for storing Typescript files within an ASP.NET Core project

My Typescript app is built on AngularJS 2 with ASP.NET Core, and currently I store my TS files in the wwwroot directory. While this setup works well during development, I am concerned about how it will function in production. I aim to deploy only minified ...

Error: Unable to access 'subscribe' property of empty object in Angular Unit Test

After making updates to an Angular component, I encountered issues with broken unit tests. All test specs are failing, leading me to believe that the problem lies in the initialization within the beforeEach calls. Despite extensive research, I have been un ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

The Text Label in React native hooks is not properly updating when using Usestate, resulting in consistently displaying the same value

I have created a weekly calendar that displays Sunday to Saturday. The issue I'm encountering is that the text value is not updating even though it changes in console.log. I've attempted using state and setState but it didn't work! Any thoug ...

The concept of ExpectedConditions appears to be non-existent within the context of

Just starting out with protractor and currently using version 4.0.2 However, I encountered an error with the protractor keyword when implementing the following code: import { browser } from 'protractor/globals'; let EC = protractor.Expe ...

Understanding DefinitelyTyped: Deciphering the explanation behind 'export = _;'

Having trouble integrating angular-material with an ng-metadata project and encountering some issues. Utilizing DefinitelyTyped for angular material, the initial lines are as follows: declare module 'angular-material' { var _: string; expo ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

What is the most effective way to inform TypeScript that my function will return a class that has been expanded by a specific class?

Imagine a scenario where we have the following classes: class A { constructor($elem: JQuery<HTMLElement>) { $elem.data('plugin', this); } inheritedMethod() { ... } } class B extends A { constructor($ele ...

Locate a specific item by its ID within a JSON file utilizing Angular version 2 or later

My JSON file structure is like the example below: { "id": "1", "country": "Brazil", "state": [ {"id": "1", "name": "Acre", "city": [ { "id": "1", "name": "Rio Branco"}, { "id": "2", "name": "Xapuri"} ...

Ways to update image source in a React application

Can you help me understand how to switch out an image source in React? I am currently assigning a src URL to my img tag. If the image is not available on the server, I would like to replace the src URL with this one: http://punemirror.indiatimes.com/photo/ ...

Definition duplication is necessary for TypeScript object properties

I'm currently facing a challenge with TypeScript as I attempt to develop a function that properly assigns default values for an optional object within another object. Even though I am setting up everything in the parameters, I keep encountering an er ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

How Can I Build a Dynamic Field Form Builder in Angular 4?

While working with dynamic JSON data, I needed to create fields dynamically. For instance, if my JSON array contains 3 values, I would generate 3 input checkboxes dynamically as shown below: <ng-template ngFor let-numberOfRow [ngForOf]="numberOfRows"&g ...