Textfield type date get year only in React

121 Views Asked by At

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}
              />
2

There are 2 best solutions below

4
Bharti Sharma On BEST ANSWER

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.

0
Akeel Ahmed Qureshi On

You can do so using JavaScript's string manipulation functions.In the handleChange function, event.target.value will give you the selected date in "YYYY-MM-DD" format. By using split('-'), you can split this string into an array where the first element is the year.

import React from 'react';
import TextField from '@material-ui/core/TextField';

const YourComponent = () => {
  const handleChange = (event) => {
    const selectedYear = event.target.value.split('-')[0];
    console.log(selectedYear);
  };

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

export default YourComponent;