How Do I Pass a Function Through A React Component For Data Sharing Between Parent and Child?

Viewed 46

I have followed this tutorial (https://www.freecodecamp.org/news/pass-data-between-components-in-react/) to the best of my ability but I am still having trouble

I am getting the following error:

Uncaught TypeError: childToParent is not a function"

Here is the parent function:

function App() {
const childToParent =(value) => {console.log(value)}
...
return (
...
  <SelectHours value={state.selectedHour} childToParent={childToParent}></SelectHours>
...
)

and the child function:

export default function SelectHours(selectedHours, childToParent) {
....
return (
<Select
  labelId="select-demo"
  id='select-demo'
  defaultValue=""
  //onChange={event => handleChange(event.target.value, true)}
  value={workHours[0] ? workHours[0] : ""}
>
  {
    workHours.map((value, index) => {
      return (
        <MenuItem
          value={value ? value : ""}
          key={index}
          onClick={() => childToParent(value)}
        >
          {value}
        </MenuItem>
      )
    })
  }
</Select>
)
....
}
3 Answers

You need to add your curly braces so react can tell its a prop.

export default function SelectHours({selectedHours, childToParent}) {
....
return (
<Select
  labelId="select-demo"
  id='select-demo'
  defaultValue=""
  //onChange={event => handleChange(event.target.value, true)}
  value={workHours[0] ? workHours[0] : ""}
>
  {
    workHours.map((value, index) => {
      return (
        <MenuItem
          value={value ? value : ""}
          key={index}
          onClick={() => childToParent(value)}
        >
          {value}
        </MenuItem>
      )
    })
  }
</Select>
)
....
}

must destruct props like this.

export default function SelectHours({selectedHours, childToParent})

or use props like this

    export default function SelectHours(props)
      ...
    onClick={() => props.childToParent(value)}

read about object destructuring in this article

https://dmitripavlutin.com/javascript-object-destructuring/

You need to have a handler for ChildToParent inside

function App() {
...
const childToParent =(value) => {console.log(value)}
return (
...
  <SelectHours value={state.selectedHour} childToParent={childToParent}></SelectHours>
...
)

the App component

Related