Home > Net >  Mantine date picker throws an objects are not valid as a react child error
Mantine date picker throws an objects are not valid as a react child error

Time:01-09

I'm trying to use mantine Date in NextJS. When a user clicks on the date, that date suppose to display the date in the html text heading. For example, if a user picks the date jan 1st 2023, the text is supposed to look like Date: Sun Jan 01 2023... I'm testing it out using a console.log and it works. However, when I try to use it in the text heading this error gets thrown: Error: Objects are not valid as a React child (found: [object Date]). If you meant to render a collection of children, use an array instead.

I tried adding a map to it that didn't work. Then I tried using const date = [...calendarVal] but it said TypeError: calendarVal is not iterable

import { useState, useEffect } from 'react';
import { Modal, Button, Group } from '@mantine/core';
import { Calendar, RangeCalendar } from '@mantine/dates';
import React  from 'react';

export default function Demo() {
  const [opened, setOpened] = useState(false);
  const [calendarVal, setCalendarVal] = useState(Date());
  const [hydrated, setHydrated] = React.useState(false);

  React.useEffect(() => {
    setHydrated(true);
  }, []);

  useEffect(() => {
    console.log(calendarVal)
  })

  if (!hydrated) {
    // Returns null on first render, so the client and server match
    return null;
  }
  
  return (
    <>
      <Modal
        opened={opened}
        onClose={() => setOpened(false)}
        title="Introduce yourself!"
      >
        {/* Modal content */}
      </Modal>

      <Group position="center">
        <Button onClick={() => setOpened(true)}>Open Modal</Button>
        
      </Group>
      
      <p>Date: {calendarVal}</p>
      <Group position='center'>
        <Calendar onChange={setCalendarVal} value={calendarVal}  />
      </Group>

    </>
  );
}

CodePudding user response:

You can't render objects directly in React, you first need to convert them to strings (typically). For instance you can write the following:

<p>Date: {calendarVal.toLocaleString()}</p>
  • Related