0

I know it's a question asked many times on SO but I am still facing a problem don't know how to resolve.

import Events from './subComponents/Events'

export default class userHome extends Component {
  constructor() {
    super();
    this.state = {
      events:[],
    };
    this.changeView=React.createRef();
  }

  changeViewClick = () =>{
    this.changeView.current.changeDataView();
  };

  render() {
    const {events} = this.state

    return (
      <IconButton onClick={this.changeViewClick}>
        <CardView  />
      </IconButton >
      <IconButton onClick={this.changeViewClick}>
        <TableView /> 
      </IconButton> 
      <Events ref={this.changeView} events={events} />
    );
  }
}

Events Component

export default class Events extends Component {
  constructor(props) {
    super(props);     
  }

  changeDataView = () => {
    console.log("hi");
  }

  render() {
    return (<div>Hey Child</div>);
  }
}

I am getting error as TypeError: _this.changeView.current.changeDataView is not a function

My reactjs version is 16.6.3

Rot-man
  • 18,045
  • 12
  • 118
  • 124
Kramer
  • 389
  • 8
  • 34

1 Answers1

0

In my opinion, have you tried to pass an anonymous function to child component ?

onClick={() => this.yourfunction()}

It happened, I think, because you called in your child component this props : this.changeView.current.changeDataView()

So when you pass that props in the child component you must passed it as an anonymous function to tell React it's a function to execute when the onClick event is triggered.

Let me know if that resolve your problem or if I am wrong

abrancato
  • 21
  • 1
  • 5
  • I did `onClick= {()=>this.changeViewClick}` but then this function is not being called – Kramer Mar 07 '19 at 09:40
  • You forgot parenthesis at the end of `this.changeViewClick` – abrancato Mar 07 '19 at 10:07
  • hey if I use like this ref={()=>this.changeView} I am getting `TypeError: Cannot read property 'changeDataView' of null` – Kramer Mar 07 '19 at 10:22
  • Try to do this: `{() => this.changeView()}` – abrancato Mar 07 '19 at 10:28
  • That is the wrong way apart from this changeView is not even a function just a reference – Kramer Mar 07 '19 at 11:16
  • Do you know how to use innerRef since I found out the problem. It was due to withStyles usage in child component – Kramer Mar 07 '19 at 11:45
  • Okay my bad, `changeView` is a reference. innerRef is not a standard React property. I didn't use this so now it's all yours. But maybe with this: `innerRef={x => (this.changeView = x)}` ? – abrancato Mar 07 '19 at 12:55
  • not working If I remove but If I don't use withStyles where I am exporting my component then it works.....I told you innerRef plays some role here I don't know quite how to use it yet – Kramer Mar 08 '19 at 09:34