What could be causing the issue with my Date and Time input not functioning correctly?

I developed a React frontend application styled with Material UI design. The issue I am facing is that after adding the Date and Time component styling to the form, it is unable to process the "name" value for posting. Specifically, the error message "TypeError: Cannot read properties of undefined (reading 'name')" appears only in the Date and time input fields. Can someone please review my code? Thank you.

function ReservationForm(){
    const navigate = useNavigate();
    const params = useParams();
    const {user}=useContext(Cont)

    
    const[reservationData,setReservationData]=useState({
        name:"",
        date:"",
        time:"",
        num:"",
        contact:"",
        occasion:"",
    });
    function handleReservationChange(event){
        setReservationData({
            ...reservationData,
            [event.target.name]: event.target.value,
        })
    }
    
    function handleReservationSubmit(event){
        event.preventDefault();
        const newReservation={
            ...reservationData,
            restaurant_id: params.id,
            user_id: user.id,
        };

        fetch(`/reservations`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(newReservation),
          })
            .then((r) => r.json())
            .then(
                setReservationData({
                name:"",
                date:"",
                time:"",
                num:"",
                contact:"",
                occasion:"",
              })
            );
          navigate("/myreservations");
        }

    
    return(
        <>
          <Box
        component="form"
        sx={{
          "& > :not(style)": { m: 1 },
        }}
        noValidate
        autoComplete="off"
        onSubmit={handleReservationSubmit}
      >
       <h1 className="editheadings">Reserve 🍽️</h1> 
      
       <FormControl className="inputstyle">
          <InputLabel htmlFor="component-outlined">Name</InputLabel>
          <OutlinedInput
            type="text"
            name="name" 
            id="name"
            value={reservationData.name} 
            onChange={handleReservationChange} 
            label="Name"
          />
        </FormControl>
        <br />
        <FormControl>
          <LocalizationProvider   name="date" dateAdapter={AdapterDayjs}  fullWidth>
            <DatePicker
            name="date"
              label="Date"
              value={reservationData.date}
              onChange={handleReservationChange}
              renderInput={(params) => <TextField {...params} />}
              
            />
          </LocalizationProvider>
        </FormControl>
        <FormControl>
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <TimePicker
   name="time" label="Time"
              value={reservationData.time} onChange={handleReservationChange}
              renderInput={(params) => <TextField {...params} />}
            />
          </LocalizationProvider>
        </FormControl>
        <br />
        <FormControl className="inputstyle">
          <InputLabel htmlFor="component-outlined">No. of Guests</InputLabel>
          <OutlinedInput
            type="number"
            name="num"
            value={reservationData.num} onChange={handleReservationChange}
          />
        </FormControl>
        <br />
        <FormControl className="inputstyle">
          <InputLabel htmlFor="component-outlined">Contact</InputLabel>
          <OutlinedInput
            type="tel"
            name="contact"
            value={reservationData.contact} onChange={handleReservationChange}
            placeholder="contact"
          />
        </FormControl>
        <br />
        <FormControl className="inputstyle">
          <InputLabel htmlFor="component-outlined">Occasion</InputLabel>
          <OutlinedInput
            type="text"
            name="occasion"
            value={reservationData.occasion} onChange={handleReservationChange}
          />
        </FormControl>
        <Stack paddingLeft={15} direction="row" id="loginbutton">
          <ColorButton variant="contained" type="submit">
            Update Reservation
          </ColorButton>
        </Stack>

       
       </Box>
        </>
    )
}
export default ReservationForm;

Answer №1

When working with the DatePicker and TimePicker components, keep in mind that their onChange events pass the new value instead of the event itself. To handle this, you'll need to create a new handleChange function specifically for these components:

function updateReservation(name, newValue) {
    setReservationData({
      ...reservationData,
      [name]: newValue
    });
}

Make sure to call this function within the DatePicker and TimePicker components like this:

<DatePicker
  name="date"
  label="Date"
  value={reservationData.date}
  onChange={(newValue) =>
    updateReservation("date", newValue)
  }
  renderInput={(params) => <TextField {...params} />}
/>

<TimePicker
  name="time"
  label="Time"
  value={reservationData.time}
  onChange={(newValue) =>
    updateReservation("time", newValue)
  }
  renderInput={(params) => <TextField {...params} />}
/>

To see how this function works in action, check out this sandbox for a live demonstration.

Answer №2

It is advisable to review this function for any inconsistencies.

function checkReservationChange(event){
        updateReservation({
            ...reservationData,
            [event.target.name]: event.target.value,
        })
    }

According to the function, each field must possess a name property. However, it appears that some fields are lacking this property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Basic Authentication Headers in React Applications and IIS Servers

Our React App is now hosted within an ASP.NET Core site on an IIS Server. Previously, the React App was hosted separately on IIS and protected by HTTP Basic Auth on our Staging server without any issues. However, after moving the React App inside the ASP. ...

"Customize your Vuetify v-card with uniquely styled rounded corners on only

I am seeking to create a unique v-card design where only two corners are rounded. Despite my attempts, the card ended up rotated by 90° and didn't achieve the desired outcome. DESIGN ATTEMPT: <div class="text-center rotate-ninety ml-n6" ...

What is the correct way to utilize a variable as a parameter in React Query while employing the axios.request(options) method?

I'm currently working on a React Query component with the following structure: function test () { const [var, setVar] = useState("") const options = { method: "GET", url: "https://api.themoviedb.org/3/search/tv" ...

Enhance Your File Uploads with Custom Images in Bootstrap

For the file upload buttons, I have used the given image by customizing the button look using Bootstrap 3. Here is an example of how I achieved this: <label class="btn btn-primary" for="my-file-selector"> <input id="my-file-selector" type="fi ...

Having difficulty aligning the container div in the center

I'm trying to create a centered grid of full-width buttons, but for some reason, I just can't seem to get the container centered. Any suggestions? Check out the code here - https://jsfiddle.net/a6qo6tzL/ Thank you! <div class="Wrapper"> ...

Numerous markers displayed on Google Maps now only reveal current information upon clicking

Hello everyone! I am currently facing an issue where multiple poppers open simultaneously when clicking on markers. I have been trying to display only one popper at a time, but haven't found any example of how to do this on the React Material site. Be ...

Utilizing GraphQL API in a React frontend: A Guide

I'm looking to build a frontend for my Graphcool API endpoint and need some guidance on how to get started with ReactJS-Graphcool. Any references or tips would be greatly appreciated! ...

What's preventing it from being cached?

So, I have a website (https://illution.dk) and most of my files that are included or linked are returning a "304 Not Modified" header. However, there is one exception: https://illution.dk/include/style.php, which always returns a "200 OK." The headers for ...

How to Turn Off Browser Autocomplete for Material-UI TextField

I am currently utilizing the country select feature from Material UI (https://material-ui.com/components/autocomplete/#country-select). One issue I have encountered is that when the user clicks on the input field, the browser's autocomplete popup cove ...

CSS: Centralizing a Div Element with Fluid Width

I've created a popup that appears in the center of the screen using: transform: translate(-50%, -50%); and position: absolute. However, I'm facing an issue where the width of the popup remains fixed instead of adjusting dynamically based on the c ...

Top method for tracking changes in numerous textboxes

I'm currently working on a form that is organized into tabs using jQuery. Each tab contains different elements of the form related to a specific section, with a save button at the bottom of each tab. I want to implement a feature where a warning icon ...

Is there a way to direct Webpack in a Next.JS application to resolve a particular dependency from an external directory?

Is it possible to make all react imports in the given directory structure resolve to react-b? |__node_modules | |__react-a | |__app-a | |__component-a | |__next-app | |__react-b | |__component-b // component-a import { useEffect } from ' ...

Error: "$$" not defined in this context

I am currently working on generating a dynamic pie chart programmatically with the intention of transforming it into a reusable React Component. The main idea is to have an interactive pie chart where each slice expands into a full pie when clicked. I came ...

Setting a default value in Autocomplete using Material UI version four

I am currently working with Material UI version 4. I have a component that displays all users in a dropdown, but I am struggling to set a default value. I tried using the following sandbox example, but it didn't work for me: [https://codesandbox.io/s ...

Next.js deployments on Vercel are encountering issues with resolving local fonts

Currently, I am facing an issue while trying to incorporate next/fonts into my project in next.js 13.3. The setup works perfectly on my local machine, but as soon as I deploy it to Vercel, a build error arises with the message Module not found: Can't ...

Utilizing Conditional Statements Within a Map Function

A DataGrid on my frontend application displays data fetched from a MongoDB backend. The data corresponds to keys defined in the MongoDB documents, each containing a set of boolean values. My goal is to check if any of these boolean values are true and disp ...

Unable to reset input in a functional component using React JS

I have a component named TextInput that is responsible for rendering an input element: function TextInput({ type = "text", label, name, required = false }) { const [value, setValue] = useState(""); function handleChange(e) { se ...

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

Using a JSON file as a database for a project featuring HTML, CSS, and Vanilla JavaScript

Our task was to create a project that exclusively utilized JSON files for data storage. The data structure we were working with resembles the following: [ { "aircraftName": "Boeing 747", "departDate": 1640173020000, ...

Utilize CSS to create a column layout

I have some HTML output that I would like to style using CSS, but unfortunately I have no control over how the HTML is generated and cannot make any changes to it. Right now, I have a two-column layout set up here: http://jsfiddle.net/uvg6f3tr/ I'm ...