0

here in my code i have 5 checkboxes that i want to push their values if they were checked but when i tick a checkbox and then tick another one an error displayes that says TypeError: Cannot read property 'value' of null

and this is my code:

import React, { useState, useEffect } from 'react';
import Label from '../../styles/Label';

function AlertReminder() {
  const [selectedReminders, setSelectedReminders] = useState([]);

  useEffect(() => {
    console.log(selectedReminders);
  }, [selectedReminders]);

  const remindersList = '1 hour before,12 hour before,24 hour before,48 hour before,1 week ago'.split(',');
  console.log(remindersList);
  const changeHandler = (e) => {
    if (selectedReminders.includes(e.target.value)) {
      selectedReminders.splice(selectedReminders.indexOf(e.target.value), 1);
      console.log(selectedReminders);
    } else {
      setSelectedReminders(selectedReminders => [...selectedReminders, e.target.value]);
      console.log(selectedReminders);
    }
  };

  return (
    <div>
      <Label>Alert Reminders:</Label>

      <form>

        {
        remindersList.map(
          (c) => (
            <label>
              {c}
              <input type="checkbox" value={c} onChange={changeHandler} />
            </label>
          )
        )
      }
      </form>
    </div>
  );
}

export default AlertReminder;

1 Answer 1

1

React uses synthetic events, it is gone by the time you are trying to use it in if/else statement.

There are three solutions:

  1. To have it persist you need to begin your changeHandler with e.persist() (just add it after const changeHandler = (e) => {).
  2. Begin changeHandler with const target = e.target and than use target instead of e.target.
  3. Begin changeHandler with const value = e.target.value and than use value instead of e.target.value working code (sandbox).

More on this in react docs. Note, in React 17 you will be used e.target.value as expected (release notes).

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, this might not be needed in the future releases React 17 reactjs.org/blog/2020/08/10/react-v17-rc.html#no-event-pooling

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.