Search code examples
reactjsdateuitextfield

Textfield type date get year only in React


Does any one know how to get only the year using the Textfield type date in react?

 <TextField
                key={"input-year"}
                InputLabelProps={{ shrink: true }}
                required
                fullWidth
                variant="outlined"
                type="date"
                label="Year"
                margin="dense"
                onChange={handleChange}
                value={formValues?.year}
              />

Solution

  • I updated the code according to requirement. Please check

    import React from 'react';
    import { FormControl, InputLabel, MenuItem, Select } from '@mui/material';
    
    const App = () => {
      const years = Array.from({ length: 10 }, (_, index) => new Date().getFullYear() - index);
        return (
          <FormControl fullWidth variant="outlined" margin="dense">
             <InputLabel htmlFor="year">Year</InputLabel>
             <Select
               label="Year"
               value={formValues?.year}
               onChange={handleChange}
               inputProps={{
                   name: 'year',
                   id: 'year',
               }}
             >
               {years.map((year) => (
                 <MenuItem key={year} value={year}>
                   {year}
                 </MenuItem>
               ))}
           </Select>
        </FormControl>
      )
    }
    
    export default App;
    

    You can manage year logic according to your requirement.