I am working on a booking app in learning purposes. I'm using React, Redux and React DatePicker. Basically, everything works well, except for passing the Date object as a prop. It throws an error message:
Error: Objects are not valid as a React child (found: Sat Nov 09 2019 16:09:32 GMT+0500 (Yekaterinburg Standard Time)). If you meant to render a collection of children, use an array instead.
I know that React can't render objects, so I tried to use "toString()" method in reducer but it didn't help. I guess I should use this method in DatePicker but I don't know how.
<DatePicker
selected={this.props.date}
dateFormat="LLL"
onChange={(day) => {this.props.setDate(day)}}
locale="ru"
inline
/>
Tell me, please, where do I need to add toString() method, so that when I select a date in the calendar, the Date object is a string and my application works fine.
The best way to turn your date object into a string is going to depend on what information you want to display. Try .toLocaleDateString()
to get a string that's formatted to the way dates are commonly written in the user's custom.
Check out MDN's Date
documentation for more options (you'll probably want one listed under the 'conversion getter' section)
For how to integrate this into React, you don't need to do the conversion in your reducer. Redux can store date objects just fine, then you can call the conversion method of choice inside your component.
Imagine, for instance, a todo item component which takes in a Date object as a prop. This object, in your case, would come from redux.
const TodoItem = ({ task, dueDate }) => (
<div>
<h2>{task}</h2>
<span>{dueDate.toLocaleDateString()}</span>
</div>
);
The other option would be to call .toLocaleDateString()
inside of your mapStateToProps
function