Search code examples
reactjsonchangearray.prototype.map

mapping through an array of objects will update all of my react-switch components when it should only update one onChange


I'm trying to make a table where I can edit store hours. I'm using the Switch component from react-switch and mapping through the days of the week. The problem is that every time I click on one switch element, all of the switch elements are all updating, however, I only want the one I'm clicking on to update.

The react-switch documentation requires an onChange and a checked prop, and it looks like I cannot pass an onClick.

Here's the element that I'm trying to render:

import Switch from "react-switch";
import  { regularHours }from '../../../helpers/momentFunctions';
import { FormGroup, Input } from "reactstrap";
import { Styles } from './Styles/EditDaysOfWeekStyles';

export const EditDaysOfWeek = () => {
    const [checked, setChecked] = useState(true);
    const handleChange = () => {
        setChecked(!checked);
    }
    return (
      <div>
        {regularHours.map(({ i, day }) => (
          <Styles>
              <div key={i}>{day}</div>
              <FormGroup key={i}>
                <Input type="text" placeholder="8:00AM" />
              </FormGroup>
              <p>-</p>
              <FormGroup key={i}>
                <Input type="text" placeholder="8:00PM" />
              </FormGroup>
              <Switch
                checked={checked}
                onChange={handleChange}
                defaultValue={true}
                onColor="#2bbbae"
                offColor="#f15a29"
              />
            </Styles>
          ))}
      </div>
    );
  };

Here's the data structure:

export const sunday = moment.weekdays(0);
export const monday = moment.weekdays(1);
export const tuesday = moment.weekdays(2);
export const wednesday = moment.weekdays(3);
export const thursday = moment.weekdays(4);
export const friday = moment.weekdays(5);
export const saturday = moment.weekdays(6);

export const regularHours = [
    {
      day: sunday,
      index: 0,
    },
    {
      day: monday,
      index: 1,
    },
    {
      day: tuesday,
      index: 2,
    },
    {
      day: wednesday,
      index: 3,
    },
    {
      day: thursday,
      index: 4,
    },
    {
      day: friday,
      index: 5,
    },
    {
      day: saturday,
      index: 6,
    }
  ];

If you need a full view - I made a sandbox to play around in: https://codesandbox.io/s/dank-leftpad-lt7y2?fontsize=14&hidenavigation=1&theme=dark


Solution

  • You're passing the same checked value and same handleChange function to every <Switch /> without differentiating between them.

    You need to have a separate checked state for each <Switch /> if you don't want them to all have the same value.

    I made some changes to your sandbox that gets it working as expected. (All edits are in Day.js)

    Edit immutable-wildflower-ny456