Steps to generate a range of years in a React Native application

I have successfully built a drop-down view for users to select their date of birth using dummy data. However, I am facing the challenge of implementing a data module for years/months/days using date-fns. Can anyone guide me on how to achieve this?

So far, I have created the drop-down component that works well with the dummy data. My main struggle is figuring out how to replace the dummy data with real date data.

Dropdown Component :

const days = [
  { num: '1', key: '1' },
  { num: '2', key: '2' },
  { num: '3 ', key: '3' },
  { num: '4', key: '4' },
  { num: '5 ', key: '5' },
];

const Dropdown = ({ label, data }) => {
  const [selecteday, setSelecteday] = useState({ item: '' });

  const DropdownButton = useRef();
  const [visible, setVisible] = useState(false);

 

  const toggleFunction = () => {
    visible ? setVisible(false) : openDropdown();
  };

  const openDropdown = () => {
  
    setVisible(true);
  };

  const onItemPress = item => {
    setSelecteday(item);
    console.log(item);
    setVisible(false);
  };

  const renderItem = ({ item }) => (
    <TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
      <Text style={styles.buttonText}>{item.num}</Text>
    </TouchableOpacity>
  );
  const renderDropdown = () => {
    return (
      <SafeAreaView style={styles.dropdown}>
        <FlatList
          data={days}
          renderItem={renderItem}
          keyExtractor={(item, index) => index.toString()}
        />
      </SafeAreaView>
    );
  };
  return (
    <>
    <View style={{zIndex: 10}} >
      <TouchableOpacity
        onPress={() => toggleFunction()}
        ref={DropdownButton}
        style={styles.button}
      >
        <Text style={styles.buttonText}>
          {' '}
          {selecteday.item === '' ? label : selecteday.num}
        </Text>
        <MaterialCommunityIcons name="chevron-down" color={'#58abc8'} size={16} />
        {visible == true ? renderDropdown() : null}
      </TouchableOpacity>

    
      </View>
        { visible ? <View 
                 style={styles.modal}>
                <TouchableOpacity
                 style ={styles.overlay}
                 onPress={toggleFunction}
                 ></TouchableOpacity>
      </View>: null}
   </>
  );
};

Answer №1

To retrieve the number of Days, Months, and Years, you can define functions like these:

const getDays = (month, year) => {
        if (month <= 12 && month >= 1) {
            const daysCount = new Date(year, month, 0).getDate();
            console.log('daysCount--', daysCount);
            const daysArray = Array(daysCount).fill('').map((element, index) => {
                return {
                    key: index + 1 + '',
                    num: index + 1,
                }
            })
            console.log(daysArray);
        }
    }

    const getMonth = () => {
        const monthCount = 12; //this is always 12 so can pass static
        const monthsArray = Array(monthCount).fill('').map((element, index) => {
            return {
                key: index + 1 + '',
                num: index + 1,
            }
        })
        console.log(monthsArray);
    }

    const getYears = () => {
        const yearsCount = 200;//you can pass more than 200
        const yearsArray = Array(yearsCount).fill('').map((element, index) => {
            return {
                key: 1900 + index + '',
                num: 1900 + index,
            }
        })
        console.log(yearsArray);
    }
    useEffect(() => {
        const selectedMonth = 5;
        const selectedYear = 2022;
        getMonth();
        getYears();
        getDays(selectedMonth, selectedYear); //first select year, month and pass selected month and year here.
    }, [])

You need to choose the year first, followed by the month. Then based on the selected month, you will receive the corresponding days in that month and convert them into the required array format.

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

Starting a fresh SSH terminal directly from a web browser

I have an SSH IP address. Is it feasible to launch an SSH terminal through a web browser, similar to clicking on a hyperlink or Google Play store link? For instance: Click Here to Open SSH Terminal Upon clicking this link, the SSH session should open an ...

`Failure to prompt an error following an unsuccessful post request in a node.js application using axios and express`

I'm currently facing an issue while trying to implement password change validation. The problem lies in not receiving the errorMessage from the server in case of an error. Although I've successfully managed to update the password and send back a ...

Using JavaScript to insert specific values into an array of floats

let floats = [6, 10, 10, 10, 20, 48, 50.5, 60, 60, 78, 90]; let evens = [{}]; for(let i = 0; i < floats.length; i++){ if(floats[i] == floats[i - 1]) { evens[evens.length - 1][i - 1] = floats[i - 1], evens[evens.l ...

How can I apply a shadow effect to a <View> element just like a regular tab bar?

My customized navigation bar is using the <View> element. https://i.sstatic.net/QA8Ad.png Is it possible to add a bottom shadow similar to the default react-navigation bar (refer to the image below)? https://i.sstatic.net/ORD8J.png I find it chal ...

Send a parameter from the web application and trigger a pop-up dialog box

Need help with passing a search term from a Google web app to display results. Facing issues with a blank screen upon submission. Looking to have the form show results when submitted. The main code functions correctly within the logger, now focusing on UI ...

The URL provided for the jQuery AJAX call is not valid

My ajax request is set up like this: $.ajax({ url: self.opts.url.replace('//www.', '//'), type: 'POST', ... }); To ensure accuracy, I included the .replace method. The URL stored in opts.url is "http://website.co ...

Guide to retrieving a string value rather than Json output with a mongodb aggregate function

I have a function that retrieves the value of the 'minHospitalization' field from the database. The response from this function is '[{"minHospitalization":1}]' Instead of returning the value in JSON format, I want to return just ' ...

What causes the issue of text being blocked by a webgl shader background even when the text div is layered above and given a higher z-index?

I am looking to enhance a WordPress theme by dynamically generating glsl shaders using the three.js library for JavaScript, and then incorporating those shaders into various HTML elements, such as using them as backgrounds for text content. My current cha ...

The variable $ has not been defined in Jquery framework

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="deployJava.js"></script> <script type="text/javascr ...

What impact does adding 'ng' in unit tests have on how promises are handled?

Here is an example of a service that utilizes $q.when to wrap a promise from a third-party library: // myService.js angular.module('myApp', []) .service('myService', function($q, $window) { var api = new $window.MyAPI(); this ...

Node.js: Enhancing Security by Sanitizing API Requests with Failed Input Validation for Future Review

I am looking for a way to sanitize failed api requests that did not pass input validation for future security audits. The data is currently in json format and needs to remain that way. Here is an example of valid json that cannot be logged to our system a ...

The change event for Bootstrap 4 switches is not functioning as expected

I am facing an issue with multiple Bootstrap 4 switches that are dynamically loaded onto the page using JS append. I need to call a function when the switch changes. The example below works fine when the switches are added in HTML, but it doesn't work ...

Strategies for transferring a JavaScript variable from a JSP to a servlet

For my reporting module, I am utilizing the google visualization API java wrapper along with image charts. To pass the url of the generated chart to a servelet, I am using the getImageUrl() method to retrieve the url and storing it in a javascript variabl ...

Should I increase the number of followers, or opt for an aggregated method to monitor them?

My system loads products using an infinite scroll, displaying 12 at a time. Sometimes, I may want to sort these products based on the number of followers they have. Here's how I keep track of the followers for each product: The follows are stored i ...

The anchor events in the DataTable are not responding when clicked, resulting in a failure to load resources

When it comes to jQuery event delegation using on() and live() functions, I have encountered a problem. I am trying to create a function that triggers when a user clicks on an element in a dataTable. Can anyone help me figure out what's going wrong? I ...

Tips for identifying whether a form contains any empty fields and, if it does, directing focus to an anchor element

Is it possible to determine if a specific form contains any input fields? What about if it doesn't have any input fields? Additional Query: Also, how can I ensure that the focus is returned to a button when the page loads if the specified condition ...

Filtering in AngularJS based on a specific ID

Currently, I am dealing with a JSON encoded response from PHP that looks like this... [ {"ID":"149","IDusr":"4","aut_more_info":"good","doc_name":"img1838142879.jpeg","doc_type":"jpg"},{"ID":"149","IDusr":"4","aut_more_info":"good","img5733250433.jpeg","d ...

In my experience, Angular will generate an error if a form tag in HTML contains special characters, such as the colon symbol ':' in the 'name' attribute

Currently, I am in the midst of a Salesforce project and I am contemplating utilizing Angular JS for its remarkable capabilities. One issue I have encountered is that Salesforce prefixes form attributes like name and id with dynamic IDs. For example, if th ...

Converting a script.js document ready function wrapper and jquery plugin methods to be compatible with React (version 16.12.0)

I'm in the process of converting an older script.js file that is used to select HTML elements in conjunction with $ jquery into React. I want to export/import it into a page component using the componentDidMount() method and pass it to jquery. However ...

Limit Table Search to Specific Dynamic Key Values in JavaScript ArrayObjects

Currently, I am in the process of developing a customized search feature that involves working with an array of objects. const data = [{ name: "Janet McKenly", age: 49, city: "Baltimore", active: "2019-02-15", ...