0

I have a checkbox component which renders multiple day checkboxes. I need to print the values of the selected checkboxes. The sample given below looks like the one:

const [state, setState] = useState({ 
    "firstName": "",
    "lastName" : "",
    "mobileNumber" : "",
    "avalabilities": [{"availabilityId": "",

    day: [
      {
        value: "sun",
        name: "Sunday"
      },
      {
        value: "mon",
        name: "Monday"
      },
      {
        value: "tue",
        name: "Tuesday"
      },
      {
        value: "wed",
        name: "Wednesday"
      },
      {
        value: "thur",
        name: "Thursday"
      },
      {
        value: "fri",
        name: "Friday"
      },
      {
        value: "sat",
        name: "Saturday"
      }
    ],
    "isChecked": false,
    "checked" : false,
    "allChecked": false,
    "error": null});

this is the console value given below

{firstName: '', lastName: '', mobileNumber: '', avalabilities: Array(1), …}
allChecked: false
avalabilities: Array(1)
0:
availabilityId: ""
day: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
close: false
disabled: false
error: null
firstName: ""
isChecked: false
isPending: false
lastName: ""
mobileNumber: ""
open: false

this is how I am trying to render the arrays

{(avalabilities ||  [{}]).map((av, index) => {
    return (
      <div key={av.availabilityId}>


<>
            {av.day.map((item) => {
              return (
                <div>
                  <input
                    checked={item.checked || false}
                    onChange={() => handleChange3(item.value)}
                    type="checkbox"
                  />
                </div>
              );
            })}
          </>

But the error on mapping with day array is coming below like this

are not valid as a React child (found: object with keys {value, name}). If you meant to render a collection of children, use an array instead.

const checkedHandler = (event) => {
        
        setState(...)
        
        //Well, here I don't know how change the particular value of the 
     array...}

Any help is highly appreciated.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Disha Singh
  • 27
  • 1
  • 2
  • 7

1 Answers1

1

If i'm correct you want to show values of each checkbox and save the respective checkbox value when we toggle any checkbox. You have avalabilities array & in each object we have another day array. I render the all the avalabilities. Now when i toggle any checkbox, i pass three things to checkHandler:

  1. e which is native event of checkbox
  2. avIndex which is index of object in avalabilities array
  3. index which is index of object in day array.

Now each day object, i set a key checked and store the value of that checkbox by getting the value from e.target.checked.

Hope this solve your problem

newState.avalabilities[avIndex].day[index].checked = e.target.checked;
import { useState } from 'react';

export default function App() {
    const [state, setState] = useState({
        firstName: '',
        lastName: '',
        mobileNumber: '',
        avalabilities: [
            {
                availabilityId: '',
                day: [
                    { value: 'sun', name: 'Sunday' },
                    { value: 'mon', name: 'Monday' },
                    { value: 'tue', name: 'Tuesday' },
                    { value: 'wed', name: 'Wednesday' },
                    { value: 'thur', name: 'Thursday' },
                    { value: 'fri', name: 'Friday' },
                    { value: 'sat', name: 'Saturday' }
                ],
                isChecked: false,
                checked: false,
                allChecked: false,
                error: null
            }
        ]
    });

    const checkedHandler = (e, avIndex, index) => {
        console.log(e.target.checked, avIndex, index);
        setState((prev) => {
            let newState = { ...prev };
            newState.avalabilities[avIndex].day[index].checked = e.target.checked;
            return newState;
        });
    };

    return (
        <>
            {state.avalabilities.map((av, avIndex) => (
                <div key={av.availabilityId}>
                    {av.day.map((item, index) => (
                        <div key={index}>
                            <input
                                checked={item?.checked || false}
                                onChange={(e) => checkedHandler(e, avIndex, index)}
                                type='checkbox'
                            />
                            <span>{item.name}</span>
                        </div>
                    ))}
                </div>
            ))}
        </>
    );
}
Nouman Rafique
  • 779
  • 1
  • 2
  • 6
  • no, the error is still existing ...react-dom.development.js:13231 Uncaught Error: Objects are not valid as a React child (found: object with keys {value, name}). If you meant to render a collection of children, use an array instead.,. any suggestion to overcome this. Its just not reading array objects – Disha Singh Apr 22 '22 at 00:48
  • https://codesandbox.io/s/kind-thompson-bedf4r?file=/src/App.js Created a sandbox. Please compare the code with mine. May be you are making some mistake. Either compare it with my code or create a sandbox so that i find & fix the issue – Nouman Rafique Apr 22 '22 at 00:55
  • i have created the codesandbox.io/s/sweet-goodall-q0vz94?file=/src/App.js Please can you check what m i doing wrong here now? I have omitted all unnecessary code for your clear perusal my code. https://q0vz94.csb.app/ – Disha Singh Apr 22 '22 at 01:48
  • Now i got it. You have created a box that acts as checkbox. You just need to add two lines. In checkbox input, add `id={item.value}`. and below that input checkbox, add `for={item.value}` in label. This will now work. – Nouman Rafique Apr 22 '22 at 02:44
  • Yeah its selecting but the problem is still there i want to send only the selected checkboxes values to server as of now the whole day object is passing in request and returning post 500 error. do i need to change the json structure like ["Sunday", "Monday"....]. then how do i make it chackable with the given code so far helped me achieve my target?? – Disha Singh Apr 22 '22 at 03:01
  • What do you want to send to server? The labels or the values of the selected checkboxes? – Nouman Rafique Apr 22 '22 at 03:19
  • I want to send the selected labels to server. Sorry for being unclear with my question so far. But you have got the requirement correctly. Please suggest me the way – Disha Singh Apr 22 '22 at 03:23
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244093/discussion-between-nouman-rafique-and-disha-singh). – Nouman Rafique Apr 22 '22 at 03:23