Eric Eric - 3 months ago 12
TypeScript Question

How to initialize state in react-native-day-picker?

I am trying to apply react-native-calendar.
My code is

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);
<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>;
);
export default MyCalendar;


Then I got Syntax Error. but I don't prefer style as shown due to some requirement of our Project manager:

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


My problem is how can I initialize the values such as from, to, startDate.
So How should I fix this issues?

Answer

We need to use block body { } if we have multiple statements for arrow functions.

Refer to Function body description of arrow functions in MDN,

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

Therefore you need to return the View component which is last statement of your MyCalendar.

And that why I remove the { } for onSelectionChange of Calendar component because we can use concise body for one line statement.


Some extra repairs.

For those variables we never reassign value, we should use const.

Refer to Enforce boolean attributes notation in JSX (jsx-boolean-value) of eslint-plugin-react rules,

When using a boolean attribute in JSX, you can set the attribute value to true or omit the value. This rule will enforce one or the other to keep consistency in your code.

That why I removed the true value for startFormMonday in Calendar.

Code after repaired as following,

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 am using Atom text editor and using eslint-config-airbnb as my styleguide. They help alot in syntax error detection.

Comments