skip to Main Content

I have calendar, If I click on day, I would like to make copy of this value and store it to Array, and if I click on another day, I would like to get current day copy and add it to array with prev day value. User can select multiple days. How can I do this? I am trying this way

const [dates, setDates] = useState([])
   console.log(dates)

   const handleClick = (e) => {
     e.preventDefault()

   const selectedDya = e.target.textContent
   console.log(selectedDya)
   setDates((prev) => ({...prev}, selectedDya))
   }


<section className='week'>
          {data[0][0].map((item, i) => (
              <span key={i}
                  onClick={handleClick}
                  className={'cell'}>
                {item}
             </span>
            ))}
        </section>

3

Answers


  1. In your click handler function, do this:

       const handleClick = (e) => {
         e.preventDefault()
    
       const selectedDya = e.target.textContent
       console.log(selectedDya)
       setDates((prev) => ([...prev, selectedDya])
       }
    

    This adds the newly selected date to your previous array.

    Login or Signup to reply.
  2. To store the selected dates in an array and accumulate the values as new dates are clicked, you need to make a few modifications

    const [dates, setDates] = useState([]);
    console.log(dates);
    
    const handleClick = (e) => {
    e.preventDefault();
    
    const selectedDay = e.target.textContent;
    console.log(selectedDay);
    
    setDates((prev) => [...prev, selectedDay]);
    };
    
    return (
    <section className="week">
     {data[0][0].map((item, i) => (
      <span key={i} onClick={handleClick} className="cell">
        {item}
      </span>
      ))}
      </section>
      );
    
    Login or Signup to reply.
  3. There are a few modifications you can make to achieve your desired functionality. Here’s an updated version of your code that should work:

    import React, { useState } from 'react';
    
    const YourComponent = () => {
      const [dates, setDates] = useState([]);
    
      const handleClick = (e) => {
        const selectedDay = e.target.textContent;
        setDates((prev) => [...prev, selectedDay]);
      };
    
      return (
        <section className='week'>
          {data[0][0].map((item, i) => (
            <span key={i} onClick={handleClick} className={'cell'}>
              {item}
            </span>
          ))}
        </section>
      );
    };
    
    export default YourComponent;
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search