Home > other >  Passing Date object is prop in react
Passing Date object is prop in react

Time:11-30

I'm trying to pass a date object as a prop in react native, and access its methods to render data.

The prop is passed as following:

 <Task
                  text={item["text"]}
                  date={item["date"]}
                  time={item["time"]}
                  reminder={item["reminder"]}
                  completed={item["completed"]}
                />

It is accessed as:

<View>
      <View
        style={[
          styles.item,
          completed
            ? { backgroundColor: "#98CBB4" }
            : { backgroundColor: "#CCC9DC" },
        ]}
      >
        <View style={styles.ciricleTitle}>
          <View style={styles.circular}></View>
          <Text style={styles.itemText}>{text}</Text>
        </View>
        <Text style={styles.itemText}>{console.log(date.date)}</Text>
        {/* <Text style={styles.itemText}>{date.getDay()}</Text> */}
      </View>
      {completed && <View style={styles.line} />}
    </View>

i tried expanding the prop with {...item['date']} but it is not working

CodePudding user response:

We have to convert string to date object, You can use new Date(date).getDay()

CodePudding user response:

Let's clarify your doubt first.

  1. sending date which is a string as a prop
  2. sending date which is an object as a prop

So, you have made the mistake here. You have sent the date string rather than as the date object and trying to access the properties.

<div>
 {
  itemList.map(({ text, date, time, reminder, completed }) => (
   <Task {...{ text, date, time, reminder, completed }} />
  ))
 }
</div>

The date you are passing here undoubtedly is a string(which is item.date)

One way to acheive what you want is, send it as a date object..

<Task
 {...{
  text,
  time,
  reminder,
  completed,
  date: new Date(date)
 }}
/>

So that,

<Text style={styles.itemText}>{date.getDay()}</Text>

would become valid.

  • Related