0

I have a Calender component, where I would like to mark a date which is the next day (nextDay). I am using react-native-calendars.

export default class CustomCalender extends React.Component {
    render() {
        const today = moment().format("YYYY-MM-DD");
        const nextDay = moment().add(1, 'days').format("YYYY-MM-DD");  // 2017-08-29

        const mark = {
            '2017-08-16': {selected: true, marked: true}
        };

        return (
            <View style={styles.container}>
                <Text style={styles.labelText}>Select a date</Text>
                <Calendar
                    minDate={today}
                    onDayPress={(day) => {
                        console.log('selected day', day)
                    }}

                    markedDates={mark}
                />
            </View>
        )
    }
}

How can I use the data of nextDay (i.e., 2017-08-29) for the mark constant instead of doing like this '2017-08-16'?

I tried this way:

const mark = {
    today: {selected: true, marked: true}
};

But instead of using the value of today (i.e., 2017-08-29), it uses today itself as the name of the key.

Robin
  • 5,366
  • 17
  • 57
  • 87
  • 2
    use bracket notation, write it like this: `const mark = { [nextDay]: {selected: true, marked: true} };` – Mayank Shukla Aug 28 '17 at 05:04
  • Possible duplicate of [Using a variable for a key in a JavaScript object literal](https://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – Mayank Shukla Aug 28 '17 at 06:15

2 Answers2

0

Define the mark as empty object first. Then assign it.

const today = moment().format("YYYY-MM-DD");
const mark = {};
mark[today] = {selected: true, marked: true};

Rereference: JavaScript set object key by variable

Hana Alaydrus
  • 2,225
  • 16
  • 19
0

A simple example might help you to understand it much better:

let foo = 'hello';
let bar = {};

//using the value stored inside foo as a key for the object
bar[foo] = 'world';
console.log(bar);

//using 'foo' directly as a key instead of the value it stored
bar = {
  foo: 'world'
}
console.log(bar);
KeshavDulal
  • 3,060
  • 29
  • 30