1

I have a HOC

import React from 'react'

class Func extends React.Component  {

  addItem = () => {
    console.log('clicked')
  } 

  render(){

  const style = {
    background: 'lightgrey',
    margin: '1rem'
  }

  return (
    <div style={style}>
      {this.props.children}
    </div>
  )
 }
}

export default Func

an I have a HOC's child

import React from 'react'
import Func from './Func'

const AddButton = (props) => {
  return (
    <Func>
      <button onClick={props.addItem}>
       ok
      </button>
    </Func>
  )
}

export default AddButton  

I'd like to pass that function (and maybe somewhat else) into child and call it here.

I see child have a nice grey background, so I think props are there. But I see in react devtools any traces of function passed to it (Props read-only Empty object). So clicking does not lead to anything. ((

If background is already there, so where is a function?

Pavel L
  • 1,857
  • 3
  • 17
  • 23
  • 2
    Which method are you missing? `onClick` or the `addItem` one? Also, this doesn't look like a HoC, I just see a component which can render children. – dubes Jul 31 '18 at 10:56
  • @dubes yes, I mean `onClick` is not working. – Pavel L Jul 31 '18 at 11:03
  • This looks like it should work. I disagree with it being marked as duplicate, but I am not sure how I can ask them to undo it. Can you try by passing `() => console.log('I was clicked')`, perhaps your props.AddButton is getting lost. Alternatively, you can also look at the [render prop pattern](https://reactjs.org/docs/render-props.html) for more explicit control – dubes Jul 31 '18 at 11:33
  • @dubes - no, still no luck. Anyway, thank U. – Pavel L Jul 31 '18 at 12:06
  • what do you pass to the AddButton prop when mounting the AddButton component (btw component and prop having the same name is a bit confusing ;)) – Benjamin Jul 31 '18 at 12:09
  • @Benjamin yes, U are right, I'm passing `addItem` prop. Just edited. Still not work, props are empty. huh – Pavel L Jul 31 '18 at 12:16
  • 1
    it will not work like that. props.addItem is searched inside AddButton's props. This link was the link dubes originally suggested: https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children. It might look complicated but I'm afraid it's the only way to automatically pass props to your chilrden by wrapping them in your custom Func element – Benjamin Jul 31 '18 at 12:39

0 Answers0