Home > front end >  TypeError: changeChecked is not a function
TypeError: changeChecked is not a function

Time:07-23

I am trying to pass changeChecked as prop from parent to this child component to capture the input element id but I am getting this error. I have mentioned the child component and parent component. Please help me to solve this error.

Child Component

import { useState, useEffect } from 'react';

const CheckBox = ({ changeChecked, section }) => {


    return (
        <>
            {section.options.map((option, optionIdx) => (
                <div key={option.value} className="flex items-center">
                    <input
                        id={`filter-${section.id}-${optionIdx}`}
                        name={`${section.id}[]`}
                        defaultValue={option.value}
                        type="checkbox"
                        defaultChecked={option.checked}
                        onChange={() => changeChecked(option.id)}
                        className="h-4 w-4 border-gray-300 rounded text-indigo-600 focus:ring-indigo-500"
                        
                    />
                    <label
                        htmlFor={`filter-${section.id}-${optionIdx}`}
                        className="ml-3 lg:text-sm min-w-0 flex-1 text-gray-500"
                    >
                        {option.label}
                    </label>
                </div>
            ))}
            
        </>
    )
}

export default CheckBox;

enter image description here

Parent Component

import CheckBox from "../pages/collections/checkbox"
export default function App() {


const filters = [
    {
        id: 'brand',
        name: 'Brands',
        options: [
            { value: 'Casio', label: 'Casio', checked: false },
            { value: 'Yamaha', label: 'Yamaha', checked: false },
        ],
    },
]

  const onChangeChecked = (id)=>{
    console.log(id)
  }

  return (
    <div className="App">
 {filters.map((section) => (
      <CheckBox section={section} changeChecked={onChangeChecked} />
 ))}
    </div>
  );
}

CodePudding user response:

This is a full example of passing a function as a prop.

Don't forget to pass the props when you are using the Input component, or you will get the same error as above.

export default function App() {

  const onHandleClick = (e)=>{
    console.log(e.target.value)
  }

  return (
    <div className="App">
      <Input  onHandleClick={onHandleClick}/>
    </div>
  );
}

function Input ({ onHandleClick }) {
  return <input onChange={(e) => onHandleClick(e)}/>
}
  • Related