Teoman shipahi
Teoman shipahi

Reputation: 23102

React pass event and parameter on anchor element

I have a anchor element in react component, I want to pass event and parameter for it. Below code did not work. It throws e.preventDefault(); not function error. How can I do this?

loadComponent(e, component) {
  e.preventDefault();
  this.setState({ componentToLoad: component });
}

<a onClick={() => this.loadComponent(this.event, <FormatName />)}>
  Format Name
</a>

Upvotes: 0

Views: 1086

Answers (2)

Ali
Ali

Reputation: 426

It can be onClick={() => this.loadComponent(<FormatName />)

the event will always come as the first parameter to your handler function

loadComponent(e, component) { e.preventDefault(); this.setState({componentToLoad = component}); }

Upvotes: 1

Roy Wang
Roy Wang

Reputation: 11270

It should be onClick={e => this.loadComponent(e, <FormatName />)}.

Your setState is wrong too:

this.setState({ componentToLoad: component });

Also, it might be better to store a state that controls the visibility of the component rather than the entire component in the state, then do conditional rendering in render:

{this.state.showComponent && <FormatName />}

Upvotes: 1

Related Questions