0

I'm currently doing a calendar using React and I'm trying to make a simple function so I don't have to write each time (00:00 - 23:00).

How can I increment every div with the class name calendar-time so it does something like this?

<div className="wrapper">
            <div className="calendar-time">
                00:00
            </div>
            <div className="calendar-time">
                01:00
            </div>
            <div className="calendar-time">
                02:00
            </div>
            <div className="calendar-time">
                03:00
            </div>
        </div>

What I tried:

render() {
    for (let i = 0; i < 23; i++) {
        return(
            <div className="calendar-time">
                {i}:00
            </div>
        );
    }

    return(
        <div className="wrapper">

        </div>
    );
  }

3 Answers 3

1
{[...Array(24)].map((_, el) => (
    <div className="calendar-time" key={el}>
      {`${('0' + el).slice(-2)}:00`}
    </div>
))}
Sign up to request clarification or add additional context in comments.

Comments

0

You need make sure that your list of elements are rendered inside your wrapper element.

It is also a good idea to add a "key" attribute if you are mapping though a list and creating a list of elements as it helps react render stuff.

render() {
    // This is just an array of numbers [0,1,2...22,23]
    const hours = [...Array(23).keys()]

    return(
        <div className="wrapper">
           {hours.map((number) => (
                   <div key={`hour-${number}`} className="calendar-time">
                     {/* some string magic to make sure the the hour is always 2 digits long */}
                     {`${('0' + number).slice(-2)}:00`}
                   </div>
               );
           )}
        </div>
    );
}

Comments

0
render() {
    let hours = "";

    for (let i = 0; i < 23; i++) {
        hours += `
            <div className="calendar-time">
                ${i}:00
            </div>
        `;
    }

    return (
        <div className="wrapper">
           {hours}
        </div>
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.